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

有帮助吗?

解决方案 2

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

其他提示

Instead of continue you should give an error (throw an exception, return -1 or whatever you mean with "give an eror").

If you want to ignore the - you can change the else clause to:

result = digit + result * 10;

If this is not being done as a programming exercise, there is a simpler solution:

  static int atoi(String tmp)
  {
      int result = Integer.parseInt(tmp);
      if(result >= 0) {
         return result;
      } else {
         throw new IllegalArgumentException("Negative string "+"\"" + tmp + "\"");
      }
  }

Substitute the appropriate exception or other action in the negative result case. If you want to just ignore '-', as in the posted code, replace the if-then-else with:

      return Math.abs(result);

This code also throws an exception for strings like "abc".

More generally, if a library method does not do exactly what you want, it is often easy to use it in a method that modifies its behavior, rather than re-writing it.

You can write code like this, of course, but you need to check that tmp is a valid number.

int atoi(String tmp) {

    int result = 0;

    int factor = tmp.charAt(0) == "-" ? -1 : 1;

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

            if (tmp.chatAt(i) < '0' ||  tmp.chatAt(i) > '9') 

                continue;

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

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

        return result * factor;
}
if(digit=='-')

With

(char)(tmp.charAt(i)

You're code is assuming there are no -'s

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

Is an optimization that's blindly clamping the 'digit' variable to a number.

You need to step through what your code is actually doing, search for an ASCII chart and work through what the subtractions of '0' does ('0' == 48), so '1' (49) - '0' (48) = 1 etc...

If you don't want to convert negative numbers then simply return 0 whenever you encounter - sign instead of looping further. Put this code before the if-else block.

     if(tmp.charAt(i)=='-')  
         return 0;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top