我正在尝试使用showInputDialog让用户在想要退出程序时输入N或n。我正在使用do-while循环,我认为我的逻辑是错误的。当我输入N或n时,程序继续运行循环。
以下是我的代码:
public static void main(String args[]) {
MyClass app = new MyClass();
String quit;
// get user input until they quit
do {
boolean validEntry1 = false;
do {
String userEntry;
double num1;
// check for valid numerical entry and catch invalid entries
try {
userEntry = JOptionPane
.showInputDialog("Enter number 1");
num1 = Double.parseDouble(userEntry);
app.setNumberOne(num1);
validEntry1 = true;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,
"Please enter a valid number");
}
} while (!validEntry1);
// gets user input for number 2
boolean validEntry2 = false;
do {
String userEntry1;
double num2;
// check for valid numerical input for num2
try {
userEntry1 = JOptionPane
.showInputDialog("Enter number 2");
num2 = Double.parseDouble(userEntry1);
app.setNumberTwo(num2);
validEntry2 = true;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,
"Please enter a valid number");
}
} while (!validEntry2);
//this method gives the result of a multiplying num1 and num2
app.output();
// prompt user to continue
quit = JOptionPane
.showInputDialog("Enter N or n to quit. Enter any other key to continue.");
} while (quit != "N" || quit != "n"); //this is where I am having issues, It continues to loop regardless of what I enter.
}// end of main
关于我哪里出错的任何建议?
有没有更好的方法让用户输入退出gui?
答案 0 :(得分:0)
退出是String
,您应该使用.equalsIgnoreCase()
进行比较。
试试这样:
while (!quit.equalsIgnoreCase("n"));
字符串是对象,因此它们使用equals
方法进行比较,或者在这种情况下,您可以使用equalsIgnoreCase
两种情况。