Comparing Strings in Java .equals()

感情迁移 提交于 2019-12-25 03:19:22

问题


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();
            }

        }

回答1:


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.




回答2:


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.




回答3:


You can use strInput != null && !strInput.isEmpty()




回答4:


you can do:

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




回答5:


Try this one

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

I hope this has been helpful.




回答6:


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();
}


来源:https://stackoverflow.com/questions/26007630/comparing-strings-in-java-equals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!