Noob Java Math Question...
I am working through the Java course over at wibit.net (GREAT programming tutorials!) Given that their forums seem to be locked for the moment, I have a question about one of their String examples here:
Code:
import java.util.Random;
class StringExample3
{
public static void main(String[] args)
{
Random rand = new Random();
String outputStr = "";
Integer n1 = new Integer(rand.nextInt());
Integer n2 = new Integer(rand.nextInt());
Integer n3 = new Integer(n1.intValue() + n2.intValue());
outputStr = n1.toString() + " + " + n2.toString() + " = " + n3.toString();
System.out.println(outputStr);
}
}
So when I run the program, most of the time n1 + n2 really does = n3. However, about one in 10 times, it does not. Basically, the output will sometimes look like this: 1603065481 + 1105661559 = -1586240256. This is clearly not right. Like I said, it's a one in 10 occurrence, but this has me wondering. Can someone explain what is going on here? I doubt that there is a math issue within the language itself, or is there? What am I missing?
Thanks,
Tom
1 Attachment(s)
Re: Noob Java Math Question...
Re: Noob Java Math Question...
You might try using long or double instead in int. I got the following info from the JAVA Tutorials
minimum value of -2,147,483,648 and a maximum value of 2,147,483,647
Re: Noob Java Math Question...
Yep.
Your ints are wrapping, so use longs or change to using BigIntegers if you can't guarantee a long will be big enough.
Re: Noob Java Math Question...
Ah! That make sense!
This is one of those things that I have learned but hadn't ever seen in practice, so I didn't recognize it when it popped up!
I appreciate your help!
-Tom
Re: Noob Java Math Question...
Here is the revised and now-properly-functioning code:
Code:
import java.util.Random;
class StringExample3
{
public static void main(String[] args)
{
Random rand = new Random();
String outputStr = "";
Integer n1 = new Integer(rand.nextInt());
Integer n2 = new Integer(rand.nextInt());
Long n3 = new Long((long)n1.intValue() + (long)n2.intValue());
outputStr = n1.toString() + " + " + n2.toString() + " = " + n3.toString();
System.out.println(outputStr);
}
}