-2

I have a method in a java program here that is giving wrong result on a simple multiplication and I am not sure what's going on. Maybe it's a setting in eclipse that I need to expand -- I just have no idea.

Simple as this: 987,654,321 * 10. Should obviously be 9,876,543,210. Instead I am getting 1,286,608,618. What in the world? The method is simply reading in characters and adding the tokenized number (not longer than 10 digits) to a list. Everything else works fine but it hates this number for some reason.

public void number(char dig, boolean lc){
    int num = Character.getNumericValue(dig);
    if(number == 0){
        number = num;
    }
    else{           
        number = number*10 + num;
    }
    if(lc){
        if(String.valueOf(number).trim().length() <= intLength){
            tokenList.add(number);
            number = 0;
            return;
        }
        else{
        System.out.println("Error in number entry. Invalid or exceeded length: " + number); 
            number = 0; 
            return;
            }   
    }
}
user1814946
  • 181
  • 2
  • 11

1 Answers1

8

Your value is far outside the range of integer. The following statement:

System.out.println(9_876_543_210L);  // This is what you are claiming should have come
System.out.println(Integer.MAX_VALUE);

prints:

9876543210
2147483647

So, when you do 987654321 * 10, the value can't fit into an int, and thus it overflows, and you get that result.

Alternative? Use long type.


See also:

Community
  • 1
  • 1
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • This fixed it. Never would have occurred to me. Will accept your answer as soon as the 10 minute minimum runs out. – user1814946 Aug 28 '13 at 20:10