Basic addition and subtraction with choices
Please help with this. I am very new to this, and I need this badly. I need to create a program where it lets you choose from addition or subtraction. This is my current program:
import javax.swing.JOptionPane;
public class RationalZ {
public static void main(String args[]) {
JOptionPane.showMessageDialog(null,
"Enter the letter A for Addition and B Subtraction");
String choice = JOptionPane.showInputDialog(
开发者_运维百科 "A=Addition B=Subtraction");
if (choice == "a") {
String strNum1 = JOptionPane.showInputDialog(
"Enter a Number");
String strNum2 = JOptionPane.showInputDialog(
"Enter a second number");
int aNum1 = Integer.parseInt(strNum1);
int aNum2 = Integer.parseInt(strNum2);
JOptionPane.showMessageDialog(null, aNum1 + aNum2);
System.exit(0);
} else {
System.exit(0);
}
}
}
What's wrong? Even in the first step I can't get it.
You might want to review the difference between the ==
operator and the equals()
method.
Addendum: It's fairly easy to find good information on Java String
comparison methods; it's a little harder to find a good explanation of why ==
with String
is usually wrong.
Addendum:
Do I use another if statement?
You've got a good if-then
statement; now you need to expand it to an if-then-else statement. Notice how you can add more if-then
statements after the else
.
精彩评论