我已经编写了一个简单的待办事项列表程序,该程序将用户通过JInputDialog输入的文本(例如:“ go shopping shopping”)添加到JList。该程序运行良好,但我想我会尝试通过以下代码阻止用户在不输入文本或仅输入空格的情况下在对话框中按“确定”:

        //if create button is pressed
    }else if(src == create){
        //show an input dialog box
        String s = JOptionPane.showInputDialog(this, "What do you want to remember?");

        /*f the length of the given string is zero, or if the length of the string without spaces
        is zero, then tell the user*/
            if(s.length() == 0 || removeSpaces(s).length() == 0){
                System.out.println("Nothing has been entered");
                JOptionPane.showMessageDialog(this, "You must enter a text value!");

            //if the string is valid, add it to the file
            }else{
                sfile.add(s);
                System.out.println("Item added to list. " + s.length());
            }

        }else if(src == close){
            System.exit(0);
        }
}

    //remove all white spaces and tabs from the string
    public String removeSpaces(String s){
        s.replaceAll("\\s+", "");
        return s;
    }
}


当用户未输入任何内容时,此代码有效并显示“未输入任何内容”对话框,但在用户输入空格时不起作用。我究竟做错了什么?

最佳答案

为什么不使用s.trim()代替removeSpaces方法呢?

} else if (src == create) {
    //show an input dialog box
    String s = JOptionPane.showInputDialog(this, "What do you want to remember?");

    /*f the length of the given string is zero, or if the length of the string without spaces
        is zero, then tell the user*/
    if (s.trim.length() == 0) {
        System.out.println("Nothing has been entered");
        JOptionPane.showMessageDialog(this, "You must enter a text value!");
        //if the string is valid, add it to the file
    } else {
        sfile.add(s);
        System.out.println("Item added to list. " + s.length());
    }

} else if (src == close) {
    System.exit(0);
}


或者您可以将删除空间方法更改为:(如Pshemo所述)

public String removeSpaces(String s){
    return s.replaceAll("\\s+", "");
}

08-18 15:07
查看更多