比较Java中的字符串.equals() [英] Comparing Strings in Java .equals()
本文介绍了比较Java中的字符串.equals()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试过滤用户的输入,以确保其最多4位数字,并且不是空字符串。无论我留空还是输入一个数字,!strInput.equals(null)
仍然是真的。我比较字符串不正确吗?
I'm trying to filter the user's input to make sure its a max of 4 digits and it's not an empty string. Whether I leave it blank or I enter a number, !strInput.equals(null)
still comes up true. Am I comparing the string incorrectly?
我也试过:!strInput.equals()
, strInput! null
和 strInput!=
虽然我认为应该是.equals(...),因为我试图比较值。
I also tried: !strInput.equals("")
, strInput != null
, and strInput != ""
though I think it should be .equals(...) since I'm trying to compare values.
private void updateFast() {
String strInput = JOptionPane.showInputDialog(null, "How many?");
if (!strInput.equals(null) && strInput.matches("\\d{0,4}"))
{
//do something
}
else
{
JOptionPane.showMessageDialog(null, "Error. Please Re-enter");
updateFast();
}
}
推荐答案
更改行:
if (!strInput.equals(null) && strInput.matches("\\d{0,4}"))
To:
if (strInput != null && strInput.matches("\\d{1,4}"))
无需检查String是否为空,正则表达式检查。
No need to check if String is empty, the regex checks that.
这篇关于比较Java中的字符串.equals()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文