为什么使用nextLine或没有nextLine
之间存在差异str == str2为false但str4 == str5为true
有一些示例代码。
Scanner scan = new Scanner(System.in);
System.out.println("Input data1");
String str = scan.nextLine();
System.out.println("Input data2");
String str2 = scan.nextLine();
String str3 = str;
String str4 = "a";
String str5 = "a";
System.out.println("str==str2 : " + (str==str2));
System.out.println("str2==str3 : " + (str2==str3));
System.out.println("str==str3 : " + (str==str3));
System.out.println("str4==str5 : " + (str4==str5));
System.out.println("");
System.out.println("str.equals(str2) : " + (str.equals(str2)));
System.out.println("str2.equals(str3) : " + (str2.equals(str3)));
System.out.println("str.equals(str3) : " + (str.equals(str3)));
System.out.println("str4.equals(str5) : " + (str4.equals(str5)));
输入相同的数据,
输出
str == str2:false
str2 == str3:false
str == str3:true
str4 == str5:true
str.equals(str2):true
str2.equals(str3):true
str.equals(str3):true
str4.equals(str5):true