从JList中删除空项

时间:2014-12-30 20:49:19

标签: java string jlist spaces

我编写了一个简单的待办事项列表程序,该程序通过JInputDialog(例如:"去杂货店购物")将用户输入的文本添加到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;  
    }
}

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

1 个答案:

答案 0 :(得分:1)

为什么不使用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+", "");
}