javafor-loopnegative-numberatoifor-else

Atoi in Java for negative values


I am writing an Atoi function in Java. It runs fine for +ve integers. But what I want is when I enter a negative integer it should give me an error. So I tried including continue statement in my class Atoi. The class implemented is:

class Atoi {

    int atoi(String tmp) {

    int result = 0;

        for (int i = 0; i < tmp.length(); i++) {

            char digit = (char)(tmp.charAt(i) - '0');

        if(digit == '-')

        continue;
        }

        else {

            result += (digit * Math.pow(10, (tmp.length() - i - 1)));
        }

    return result;

    }
}   

But unfortunately it gives me the negative equivalent of the character i.e for -12 it gives me 655312! Help.

EDIT: Suppose I need to check for floating point numbers what should I do? If I enter 12.1 or 123.2 it should return 12.1 and 123.2 repectively!!


Solution

  • Quick fix for the obvious problem: the order of the logic was wrong...

    Instead of

        char digit = (char)(tmp.charAt(i) - '0');
        if(digit=='-')
        continue;
    

    try

        char origChar=tmp.charAt(i);
        if(origChar=='-')
            continue;
        char digit = (char)(origChar - '0');
    

    But there are two more problems:

    Don't forget to test with incorrect inputs too, and as @Klaus suggested, don't hesitate to throw an exception, (preferably IllegalArgumentException) with a correct error message, if an incorrect input is given to the function...