【问题标题】:Why does it not print anything when pressing "y" and enter? [duplicate]为什么按“y”并输入时不打印任何内容? [复制]
【发布时间】:2012-11-27 18:28:25
【问题描述】:

可能重复:
How do I compare strings in Java?

我真的不明白为什么当我写“y”并按回车时,下面的程序没有显示任何内容。

import java.util.Scanner;

public class desmond {
    public static void main(String[] args){
        String test;
        System.out.println("welcome in our quiz, for continue write y and press enter");
        Scanner scan = new Scanner(System.in);
        test = scan.nextLine();
        if (test == "y") {
            System.out.println("1. question for you");
        }
    }
}

【问题讨论】:

  • if中使用test.equals("y")

标签: java string if-statement


【解决方案1】:

使用equals()比较字符串

喜欢

test.equals("y")

even better

"y".equals(test)

【讨论】:

    【解决方案2】:

    您(通常)需要将字符串与 Java 中的equals 进行比较:

    if ("y".equals(test))
    

    【讨论】:

      【解决方案3】:

      你能用 == 比较字符串吗?是的。 100% 的工作时间?没有。

      当我开始使用 java 编程时,我学到的第一件事就是从不使用 == 来比较字符串,但是为什么呢?让我们进行技术解释。

      String 是一个对象,如果两个字符串具有相同的对象,方法 equals(Object) 将返回 true。 == 运算符只有在两个引用 String 引用都指向同一个对象时才会返回 true。

      当我们创建一个 String 时,实际上是创建了一个字符串池,当我们创建另一个具有相同值的 String 字面量时,如果 JVM 需求在 String 池中已经存在一个具有相同值的 String,如果有的话,你的变量是否指向同一个内存地址。

      因此,当您使用“==”测试变量“a”和“b”的相等性时,可能会返回 true。

      例子:

      String a = "abc" / / string pool
      String b = "abc"; / * already exists a string with the same content in the pool,
                                        go to the same reference in memory * /
      String c = "dda" / / go to a new reference of memory as there is in pool
      

      如果您创建字符串以便在内存中创建一个新对象并使用“==”测试变量 a 和 b 的相等性,则它返回 false,它不指向内存中的同一位置。

      String d = new String ("abc") / / Create a new object in memory
      
      String a = "abc";
      String b = "abc";
      String c = "dda";
      String d = new String ("abc");
      
      
      a == b = true
      a == c = false
      a == d = false
      a.equals (d) = true
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-11
        • 1970-01-01
        • 2014-12-15
        • 1970-01-01
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        相关资源
        最近更新 更多