Question

Here is my task. I have no idea how to implement this method.

Implement a method of Integer parseInt (String str) throws NumberFormatExceptionwhich will take the input string, which must contain onlynumbers and do not start from zero, and return a number, which must beobtained from the conversion of the line. not allowedthe use of methods of default classes Java. that's how I solved it:

public class Pars {

public static void main(String[] args) {
    String s = " ";
    int res = 0;

    int[] arr = new int[s.length()];
    try {
        for (int i = 0; i < s.length(); i++) {
            arr[i] = s.trim().charAt(i);
        }

        try {
            for (int i = arr.length - 1, j = 1; i >= 0; i--, j *= 10) {
                if ((arr[0] - 48) <= 0 || (arr[i] - 48) >= 10) {
                    throw new NumberFormatException();
                } else {
                    res += (arr[i] - 48) * j;
                }
            }
            System.out.println(res);
        } catch (NumberFormatException n) {
            System.out.println("Enter only numbers .");
        }

    } catch (StringIndexOutOfBoundsException str) {
        System.out.println("Don't enter a space!");
    }

}

}

Was it helpful?

Solution

A solution for this task can be found here. The source code for parsing a String to an int could look like:

public int ConvertStringToInt(String s) throws NumberFormatException
{
    int num =0;
    for(int i =0; i<s.length();i++)
    {
        if(((int)s.charAt(i)>=48)&&((int)s.charAt(i)<=57))
        {
            num = num*10+ ((int)s.charAt(i)-48);
        }
        else
        {
            throw new NumberFormatException();
        }

    }
    return num; 
}

OTHER TIPS

This can be achieved by reading each character in the string from left which is nothing but index of zero.

This is one way of solving the problem. I don't want to give code so that you will get a chance to work at it.

set n = 0;
for(int i = 0; i < inputStr.length(); i++)
{
    find ascii value of the character;
    if the ascii value is not between 48 and 57 throw a number format exception;
    if valid substract 48 from the ascii value to get the numerical value;
    n = n * 10 + numerical value calculated in previous step;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top