简体   繁体   中英

Comparing Strings in Java .equals()

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.

If you leave an input value blank, the string will be "" not null. You will need to use !strInput.equals("") to accomplish what you are trying to achieve.

Just in case.. you might want to .trim() your string.

您可以使用strInput != null && !strInput.isEmpty()

you can do:

strInput!=null && strInput.trim().length()>0

Try this one

if (!strInput.isEmpty() ...
if (strInput != null && strInput.length() > 0 ...

I hope this has been helpful.

You are comparing it wrong.

When you pass an object to String.equals(Object o), one of the things it will do is to check if the parameter passed is an instance of String.class. Since you are passing null, it will always return false.

You should check to see if your string is null and then if it is empty. String.class does have that method.

So:

if(strInput != null && !strInput.isEmpty() && strInput.matches("\\d{0,4}")) {
    // do something...
} else {
    JOptionPane.showMessageDialog(null, "Error. Please Re-enter");
    updateFast();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM