[英]What am I missing here? Looping with dialog boxes
I am not sure why this code is not working. 我不确定为什么此代码无法正常工作。
I am suppose to have another dialog box appear after the user selects yes or no, but whenever I run the program, it asks for y or no and then nothing happens after. 我想在用户选择“是”或“否”后出现另一个对话框,但是每当我运行该程序时,它都会询问“ y”或“否”,然后什么也没有发生。
Any ideas on what I need to do? 关于我需要做什么的任何想法?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int max = 0;
int min = Integer.MAX_VALUE;
String number;
boolean yn = true;
do {
number = JOptionPane.showInputDialog("Please enter a number");
int num = Integer.parseInt(number);
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
System.out.println(min + " " + max);
JOptionPane.showInputDialog("Would you like to enter another number? (y/n)");
String ny = in.nextLine();
if (ny.equals("n")) {
yn = false;
}
JOptionPane.showInputDialog(ny);
} while (yn == true);
JOptionPane.showMessageDialog(null, "The max number is " + max + " and the mininum number is " + min);
}
} }
The program stops on 该程序在
String ny = in.nextLine();
waiting for input from System.in based on the Scanner defined on the first line. 等待System.in根据第一行定义的扫描程序输入。
If you enter 'n' on the console and press enter then the program carries on and shows the next dialog box. 如果在控制台上输入“ n”并按Enter,则程序将继续并显示下一个对话框。
I guess you meant to say: 我想你是想说:
String ny = JOptionPane.showInputDialog("Would you like to enter another number? (y/n)");
The issue you are having is that you are not accepting the input from the panel, and are instead taking it from the console. 您遇到的问题是您不接受来自面板的输入,而是从控制台获取它。 To solve this, set ny to be equal to the input from the JPane, like so:
要解决此问题,请将ny设置为等于JPane的输入,如下所示:
String ny = JOptionPane.showInputDialog("Would you like to enter another number? (y/n)");
However, there is another issue, which is this line: 但是,还有另一个问题,就是这一行:
JOptionPane.showInputDialog(ny);
It creates a pane that you don't need that displays y or n, and doesn't accept input. 它会创建一个不需要的窗格,该窗格显示y或n,并且不接受输入。 This line doesn't need to be there, so you should remove it.
该行不需要在那里,因此您应该将其删除。 Your code works fine otherwise.
否则,您的代码可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.