Java 为什么按“时不打印任何内容?”;“是”;然后进去?
可能重复:Java 为什么按“时不打印任何内容?”;“是”;然后进去?,java,string,if-statement,Java,String,If Statement,可能重复: 我真的不明白为什么当我写“y”并按enter键时,下面的程序没有显示任何内容 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");
我真的不明白为什么当我写“y”并按enter键时,下面的程序没有显示任何内容
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");
}
}
}
使用equals()
比较字符串
像
您(通常)需要比较Java中等于的字符串:
if ("y".equals(test))
你能用==比较字符串吗?对工作100%的时间?没有
当我开始用java编程时,我学到的第一件事就是从不使用==来比较字符串,但为什么呢?让我们来做一个技术解释
字符串是一个对象,如果两个字符串具有相同的对象,则方法equals(object)将返回true。==运算符仅在两个引用字符串引用指向同一对象时才返回true
当我们创建一个字符串时,实际上是创建了一个字符串池;当我们创建另一个具有相同值的字符串时,如果JVM需求在字符串池中已经存在一个具有相同值的字符串(如果有的话),那么您的变量是否指向相同的内存地址
因此,当您使用“==”测试变量“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
在if
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
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