【发布时间】: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,因为字符串是不可变的,但会返回新字符串。