Java giving wrong result -
i have method in java program here giving wrong result on simple multiplication , not sure what's going on. maybe it's setting in eclipse need expand -- have no idea.
simple this: 987,654,321 * 10. should 9,876,543,210. instead getting 1,286,608,618. in world? method reading in characters , adding tokenized number (not longer 10 digits) list. else works fine hates number 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; } } }
your value far outside range of integer. following statement:
system.out.println(9_876_543_210l); // claiming should have come system.out.println(integer.max_value);
prints:
9876543210 2147483647
so, when 987654321 * 10
, value can't fit int
, , overflows, , result.
alternative? use long
type.
see also:
Comments
Post a Comment