-4

For a mini game in where the user tries to guess a name. But when I want to compare two text strings just to check if are the same it seems that doesn't work.

    final String miName = "Jhon";
    Scanner input = new Scanner(System.in);
    System.out.println("Guess my name: ");

    while (true) {
     String attempt = input.next();
     if(attempt == miName) {
       System.out.println("Congrats!");
       break;
     } else {
       System.out.println("Try it again!");
     }
    }

The output:

Guess my name:: 
Karl
Try it again!
jhon
Try it again!
Jhon
Try it again!
mcGuffin
  • 69
  • 1
  • 11

1 Answers1

0

You need to use .equals in case of String.

== gives true only when both the object's address match (or in case of primitive types). Object class inherently compares the address in the .equals method and you need to override the .equals method if in case you wish to write your own custom logic for equality of two objects.

Classes like String, Integer, etc. have their equals already overridden.

Parijat Purohit
  • 921
  • 6
  • 16