public void play () {
int anInteger;
//guess return code
int code;
while (true) {
String input=null;
input = JOptionPane.showInputDialog("Please enter an integer");
if (input == "-1") {
//JOptionPane.showMessageDialog(null, input);
System.exit(0);
break;
} else {
if (input==null) {
System.exit(0);
} else if (input.isEmpty()) {
continue;
} else {
anInteger = Integer.parseInt(input);
code = this.oneGuess (anInteger);
//JOptionPane.showMessageDialog(null, anInteger);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想,如果用户输入-1,显示程序将不再提示消息框.上面是我提出的代码,到目前为止.为什么它不起作用?
小智 7
字符串比较不适用于"=="运算符,使用"String.equals(Object)"函数
input.equals("-1");
Run Code Online (Sandbox Code Playgroud)
更好的方式
"-1".equals(input);
Run Code Online (Sandbox Code Playgroud)
因为它也负责空输入