开发者

How to compare multiple words separated by comma in an if statement? [duplicate]

This question already has answers here: How do I compare strings in Java? 开发者_开发问答 (23 answers) Closed 8 years ago.

I have a variable named title which is having the value "Javascript,XML,XHTML,CSS,Ajax". I need to compare in an if statement if the title equals to the above value some code needs to be run.

I have used

if (title == "Javascript,XML,XHTML,CSS,Ajax"){

} else if (title == " ") {

} else {

}

When the title is null, the code goes to the second else part and gets the correct result. But when the title is equal to Javascript,XML,XHTML,CSS,Ajax the code goes to the last else part instead of going to the if part.

What mistake have I done here? I have checked the upper lower case and also spelling along with the delimiter comma the string is same just as in the variable title. Then why do I not get the correct answer.


The == comparison operator is not correct way to compare string contents. You should instead use the .equals method:

if (title.equals("Javascript,XML,XHTML,CSS,Ajax")) {


You are using == to compare strings. You have to use title.equals("Javascript, ...") for string comparison; otherwise, you are checking to see if they are in fact the same object in memory.


If you're using Java, you'll need to use if (title.equalsIgnoreCase("Javascript,XML,XHTML,CSS,Ajax")). The equals operator is used to determine if two pointers have the same value (i.e. point to the same object).


if(title.equals("Javascript,XML,XHTML,CSS,Ajax")) {
....
}

Another advice, you should take a look at some basic Java first!


In Java, strings are objects. The == operator tells you whether they are the same instance of the same object. Use the equals(...) method for this instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜