按“y”并输入时,为什么不打印任何内容?

时间:2012-11-27 18:28:26

标签: java string if-statement

  

可能重复:
  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");
        }
    }
}

3 个答案:

答案 0 :(得分:3)

使用equals()比较字符串

test.equals("y")

even better

"y".equals(test)

答案 1 :(得分:2)

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

if ("y".equals(test))

答案 2 :(得分:1)

你能用==来比较String吗?是。 100%的工作时间?否。

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

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

当我们创建String时,字面上创建了一个字符串池,当我们创建另一个具有相同值的字符串文字时,如果JVM需求已经存在,则字符串池中具有相同值的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
相关问题