【问题标题】:Removing empty items from a JList从 JList 中删除空项目
【发布时间】:2014-12-30 20:49:19
【问题描述】:

我编写了一个简单的待办事项列表程序,它将用户通过 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;  
    }
}

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

【问题讨论】:

  • 使用 s.trim() 来删除空白区域怎么样?
  • s.replaceAll("\\s+", ""); 不会影响s,因为字符串是不可变的,但会返回新字符串。

标签: java string jlist spaces


【解决方案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+", "");
}

【讨论】:

    猜你喜欢
    • 2016-07-07
    • 1970-01-01
    • 2012-03-13
    • 2011-07-09
    • 2015-11-16
    • 2014-05-09
    • 1970-01-01
    • 2019-05-12
    相关资源
    最近更新 更多