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!");
}
}
用户必须输入正确的 key ,但代码不起作用,我不明白为什么?
屏幕截图:
最佳答案
== 运算符仅对于基元始终正确工作。即 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
除非绝对必要,否则避免每次迭代时都在循环中创建新对象。对象创建需要内存。
关于java - 如何检查用户输入的字符串是否正确? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62366511/