Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare multiple strings? [duplicate]

Tags:

java

I was wondering how I can compare multiple strings in one line. I tried using the || but it doesn't work for booleans or strings. this is what my code is like:

}else if(question != "a" || "b") {
    System.out.println("Sorry that isn't an A or a B");

For those who marked it duplicate, I checked over 200 questions here on stack overflow, and none worked. The one @Chrylis posted actually didn't help. they were just asking about the difference in == and .equals()

like image 798
SaraMaeBee Avatar asked Nov 20 '13 00:11

SaraMaeBee


1 Answers

First of all, don't use == for strings. You'll learn why later. You want to compare strings by their contents, not where they are in memory. In rare cases a string of "a" could compare false to another string called "a".

Second, split it up so you are performing boolean logic on the comparison results:

else if(!(question.equals("a") || question.equals("b")) {
like image 166
nanofarad Avatar answered Sep 27 '22 19:09

nanofarad