0

If, String, and Scanner

Why after entering "YES" into the console the condition from the first "IF" is not displayed It is always returned "ELSE": Scanner scan = new Scanner(System.in); String odp = scan.next(); if (odp == "YES"){ System.out.println("Print 1"); } else if (odp == "NO"){ System.out.println("Print 2"); } else{ System.out.println("Anything else"); } In the case of "int" everything works as it should. For example: Scanner scan = new Scanner(System.in); int odp = scan.nextInt(); if (odp == 1){ System.out.println("Print 1"); } else if (odp == 2){ System.out.println("Print 2"); } else{ System.out.println("Anything else"); }

30th Jun 2021, 8:20 AM
Łukasz Szenajch
Łukasz Szenajch - avatar
2 Antworten
+ 4
You need to use equals() method instead of `==` operator to compare strings. if (odp.equals("YES")){ System.out.println("Print 1"); } .... https://www.sololearn.com/learn/Java/2178/?ref=app
30th Jun 2021, 8:29 AM
Simba
Simba - avatar
+ 2
int is a primitive type. you understand this from the fact that it starts with a lowercase letter. therefore a variable of type int contains exactly the value you assign to it. String is a class, you understand it from the fact that its name begins with a capital letter, although objects of class String have some privileges more than other classes (being instantiated without the explicit use of new, for example). so you are in front of a referent type. therefore == verifies if the two strings are the same object, ie they contain the same memory address where the object is stored and not if they have the same content. to verify the equality of content, use the equals method as indicated to you.
30th Jun 2021, 10:26 AM
Ciro Pellegrino
Ciro Pellegrino - avatar