如何检查用户是否输入了合适的字符串? (Java)

How to check whether the user entered the appropriate string? (Java)

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!");

    }
}

用户必须输入正确的密钥,但密码不起作用,我不明白为什么?

屏幕截图:

enter image description here

== 运算符仅对原语始终正确工作。即 char、boolean、int double、float、byte、long、short。它不适用于 类,例如 String 或 Object。

而是使用:object.equals(anotherObject); 像这样

    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

并避免在每次迭代时都在循环中创建新对象,除非您绝对必须这样做。对象创建需要内存。