Chandeep Chandeep - 2 months ago 11
Java Question

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!!

Answer

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:

  • it does not negate the value, in case of a '-' character is present!
  • what if this is the input string: -1-2-3-4-5? The result will be interesting! EDIT: try this input also: 'rĂ©pa'... Even more interesting result!

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...