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:
int atoi(String tmp)
for (int i =0; i < tmp.length(); i++)
char digit = (char)(tmp.charAt(i) - '0');
result += (digit * Math.pow(10, (tmp.length() - i - 1)));
Quick fix for the obvious problem: the order of the logic was wrong...
char digit = (char)(tmp.charAt(i) - '0'); if(digit=='-') continue;
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...