繁体   English   中英

JOptionPane。 程序不显示错误信息

[英]JOptionPane. Program does not display the error message

我有要求输入用户名和密码的代码。 只是一个简单的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;
}

关于这个问题:

还有没有办法检查showInputDialog中的输入是否为字符串?

showInputDialog()返回String(偶数),并将其读取为String。

尝试声明

String name = "";

代替

String name = null;

然后在循环条件和if条件中检查字符串名称是否为空。

while (name.equals(""))

...

if (name.equals(""))

那是因为方法showInputDialog返回一个String,并且比较字符串的正确方法是使用objectString.equals(anotherObjectString),您正在比较从showInputDialog返回的String与null,但始终返回false。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM