Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

illegalargumentexception - Java - Trying to throw an error based on 2 string values in the parameter

I am trying to validate a parameter based on 2 conditions. must be a string , case insensitive. If the parameter does not equal "title" or "author" it should throw an error. The first part of the code seems to work but the second part is saying its always true and I get an error every time. Here is part of the code.

if(!"title".equalsIgnoreCase(property))
    {
       throw new IllegalNovelPropertyException("Bad Property");
    }

if(!"author".equalsIgnoreCase(property))
    {
        throw new IllegalNovelPropertyException("Bad Property");
    }
question from:https://stackoverflow.com/questions/65949046/java-trying-to-throw-an-error-based-on-2-string-values-in-the-parameter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the code is working, great. However, you may want to write

if(!property.equalsIgnoreCase("title") && !property.equalsIgnoreCase("author")) {}

There are two changes:

First, the if(! ) statements are combined into if(! && ! ). That is simpler and avoids writing unnecessary statements.

Second, if(!"title".equalsIgnoreCase(property)) is changed to if (!property.equalsIgnoreCase("title"))

Writing the variable left of the . and the compared string as the parameter of equalsIgnoreCase() is the more common notation; maybe it is a matter of preference and not of logic, though it could just as easily be a matter of practicality. Look into it, or just change it to the common notation to be safe. Intuitively, they seem the same: your way: if (!variable == string) common way: if (!string == variable) *Note that for the purposes of this logicking,

== = .equals() :)

That's amusingly redundant, so more clearly:

== is the same as .equals()

Also note that (== == .equals()) = false :) in Java,

Namely that ==, a boolean comparator, does not equal .equals(), a string comparator utilizing boolean comparison. You can use == to compare strings, but .equals() is more powerful: as you have experienced, it can utilize more advanced comparison such as .equalsIgnoreCase().

With that background, the original logic can be put even more simply:

your way: if (!b == a){}

common way: if (!a == b){}

If you reduce it to these statements, the two notations appear equal.

All of that simply serves to say that you might want to rearrange your syntax; if you still get the error let us know.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...