Page 1 of 1

Numbers

Posted: Fri Oct 30, 2009 4:02 am
by EliteCaptain01
Hi, I'm a complete newcomer to Textpad and I don't know how to add numbers.

Here's my code so far:

import javax.swing.JOptionPane;

public class ThreeNumbers
{
public static void main(String[] args)
{
String s1 = JOptionPane.showInputDialog("Enter the first number:");
String s2 = JOptionPane.showInputDialog("Enter the second number:");
String s3 = JOptionPane.showInputDialog("Enter the third number:");

int num1 = Integer.parseInt(1);
int num2 = Integer.parseInt(1);
int num3 = Integer.parseInt(1);

total = num1 + num2 + num3;

System.out.println ("The answer is " + total);


}
}



------------------------------

Can someone please lay out the exact code for how I add num1 2 and 3 and get the total to display when I run and compile it.

Thank you!

Posted: Fri Oct 30, 2009 10:29 pm
by MudGuard
String s1 = JOptionPane.showInputDialog("Enter the first number:");
String s2 = JOptionPane.showInputDialog("Enter the second number:");
String s3 = JOptionPane.showInputDialog("Enter the third number:");
So you fetch 3 Strings from the user.
int num1 = Integer.parseInt(1);
int num2 = Integer.parseInt(1);
int num3 = Integer.parseInt(1);
That's a mighty complicated way to set the variables num1, num2 and num3 to value 1.
Probably you want to use the Strings you fetched from the user as arguments of the parseInt calls ...


You don't validate the user's input, so he could give "foo", "bar", "baz" when he is asked for input. And your program would crash when trying to Integer.parseInt("foo") ...