Java: how to compare multiple lines?

I was wondering how I can compare multiple lines on one line. I tried to use || but it does not work for booleans or strings. this is my code:

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

For those who marked it as a duplicate, I checked over 200 stack overflow questions here and no one worked. In fact, this @Chrylis did not help. they were just asking about the difference in == and .equals ()

+4
source share
6 answers

First of all, do not use ==for strings. You will find out why later. You want to compare strings by their contents, not where they are in memory. In rare cases, a string "a"may compare false with another string with a name "a".

-, , :

else if(!(question.equals("a") || question.equals("b")) {
+6

Arrays.asList():

else if (!Arrays.asList("a", "b").contains(question)) {
    ...
}
+2

: || ( &&). , .

-, equals String, == ( !=), == , , .

} else if (!("a".equals(question) || "b".equals(question)))

List contains, :

} else if (!Arrays.asList("a", "b").contains(question))
+1

, equals , ==

, ||

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

You cannot do NOT equals a OR b
you must doNOT(equals a OR equals b)

Secondly, you are comparing strings with !=, but you must compare strings using the method. equals(String). This has been said millions of times, but: ==and !=compare object references, while .equals(String)comparing String values.

0
source
String[] options = {"a", "b"}; // Must be sorted.
if (java.util.Arrays.binarySearch(options, question) < 0) {
  System.out.println("Sorry that isn't an A or a B");
}

Alternatively (if your lines do not contain |:

if ("a|b".indexOf(question) == -1) {
  System.out.println("Sorry that isn't an A or a B");
}
0
source

All Articles