0
package com.company;

import java.lang.String;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String str = "";
        do{
            Scanner input = new Scanner(System.in);
            System.out.print("Input: ");

            str = input.nextLine();
        }while(str != "key123");

        System.out.print("Good!");

    }
}

The user must enter the correct key, but the code doesn't work and I can't figure out why?

Screen shot:

enter image description here

Lev145
  • 55
  • 2
  • 8
  • 1
    Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – fjsv Jun 13 '20 at 23:06
  • you just need to replace `}while(str != "key123");` with `}while(str.equals"key123");`. – fjsv Jun 13 '20 at 23:07

1 Answers1

0

The == operator works correctly all the time for primitives only. That's char, boolean, int double, float, byte, long, short. It does not work for classes like String or Object.

Instead use: object.equals(anotherObject); like so

    String str = "";
    Scanner input = new Scanner(System.in);
    do {
        System.out.print("Input: ");
        str = input.nextLine();
    } while (!str.equals("key123"));

    System.out.println("Good!");
    System.out.println(str == "key123"); // false
    System.out.println(str.equals("key123")); // true

And avoid creating a new object in a loop every time it iterates unless you absolutely have to. Object creation takes memory.

Ivan Dimitrov
  • 332
  • 1
  • 10