【问题标题】:How to check whether the user entered the appropriate string? (Java) [duplicate]如何检查用户是否输入了正确的字符串? (Java)[重复]
【发布时间】:2020-06-13 23:00:11
【问题描述】:
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

【问题讨论】:

标签: java string java.util.scanner


【解决方案1】:

== 操作符始终只对原语正常工作。那是 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

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

【讨论】:

    猜你喜欢
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多