使用Scanner时字符串比较失败

1 java string loops input

我在网上看过,所有的教程/问题都指向了我.我不明白为什么这不起作用.任何帮助将非常感激.谢谢

import java.util.*;

public class test {
    static Scanner userInput = new Scanner(System.in);
    public static void main(String[] args) {
        String textEntered = userInput.next();
        if (textEntered == "hello") {
            System.out.println("Hello to you too!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我输入"你好"但没有打印.我也试过next()和nextLine();

T.J*_*der 6

有几件事:

  1. 您在问题标题中说过"while loop",但while代码中没有循环.因此它只会检查您键入的第一个令牌,而不是后续令牌.

  2. 在Java中,您不使用==比较字符串,而是使用该equals方法(或有时equalsIgnoreCase).

    更改

    if (textEntered == "hello") {
    
    Run Code Online (Sandbox Code Playgroud)

    if (textEntered.equals("hello")) {
    
    Run Code Online (Sandbox Code Playgroud)

    ==当与对象实例(和String实例是对象)一起使用时,运算符会检查两个操作数是否指向同一个对象,因此如果使用它来比较具有相同字符序列的两个不同 String对象,则不然.