java - JOptionPane。程序不显示错误信息

标签 java string swing try-catch joptionpane

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

相关文章:

java - org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException - 写入 docx 时出错

Java 正则表达式不适用于可能值的操作数组

java - 内容更改时 Swing 组件重叠

c - 在 C 中使用正则表达式

java - 具有可选域轴和缩放的 JFreeChart

java - 从 jTable 获取单个 INT 值

java - 如何使图像在碰撞时消失然后重新出现在屏幕上的随机位置

java - 从 Java 中的已知参数创建 RSA key

java - 我应该使用哪种服务?

string - 在PLSQL中提取URL路径段字符串