我有这段代码要求输入用户名和密码。只是一个简单的 JOptionPane。该程序应该要求输入,如果用户没有在用户名中输入任何内容,它应该显示错误消息并显示相同的先前对话框要求输入用户名。但是,它不是那样工作的。即使我没有输入任何内容,它仍然会进入密码对话框。请检查我的逻辑,我可能有点困惑;还有一种方法可以检查 showInputDialog
中的输入是否为字符串?有点像整数的 NumberFormatException
? catch 方法上的异常也不起作用。 :) 提前致谢。
public class SwingExercise {
public static void main(String[] args) {
String name = null;
boolean input = true;
try {
while (input) {
while (name == null) {
name = JOptionPane.showInputDialog(null, "Enter username:");
if (name == null) {
JOptionPane.showMessageDialog(null, "No input.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
String pw = JOptionPane.showInputDialog(null, "Enter password:");
input = false;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Invalid input.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
最佳答案
这应该可以解决问题:
if(name == null || name.equals("")) {
JOptionPane.showMessageDialog(null, "No input.", "Error", JOptionPane.ERROR_MESSAGE);
name = null;
}
关于这个问题:
is there also a way to check if the input in the showInputDialog is a string?
showInputDialog()
返回 String,偶数,它将它们读取为 String。
关于java - JOptionPane。程序不显示错误信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9826519/