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?
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();
}
}
解决方案
Change the line:
if (!strInput.equals(null) && strInput.matches("\\d{0,4}"))
To:
if (strInput != null && strInput.matches("\\d{1,4}"))
No need to check if String is empty, the regex checks that.