繁体   English   中英

使用扫描仪时字符串比较失败

[英]String comparison fails while using Scanner

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

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();

有两件事:

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

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

    更改

     if (textEntered == "hello") { 

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

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

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

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

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

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

尝试使用类似的东西。

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

这可能会帮助您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM