使用Scanner时字符串比较失败

时间:2012-10-13 09:31:02

标签: 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!");
        }
    }
}

我输入“你好”但没有打印。我也试过next()和nextLine();

3 个答案:

答案 0 :(得分:6)

有几件事:

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

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

    更改

    if (textEntered == "hello") {
    

    if (textEntered.equals("hello")) {
    

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

答案 1 :(得分:1)

在java中,您无法通过==运算符比较字符串,您需要使用stringOne.equals(stringTwo)

==将比较ObjectLocation,其中.equals()比较java中String类提供的实际字符串

答案 2 :(得分:-1)

它可能无法正常工作的原因是因为您没有比较实际的字符串值。

http://www.leepoint.net/notes-java/data/strings/12stringcomparison.html

尝试使用类似的东西。

 if (textEntered.compareTo("hello") > 0) {
    System.out.println("Hello to you too!");
}

这可能会帮助你。