剛學java沒多久,遇到一個比較基礎的問題,搞不清楚產生的原因,希望能得到解答!謝謝。
System.out.println((StuArr[i].SName=="張三"));System.out.println((findName=="張三"));這2條語句,第一條是ture,第二條是false。StuArr[i].SName是把一個對象賦給了StuArr[i],然后該對象有SName成員。內容是"張三"。findName是String類型,賦值的內容是br.readLine(),鍵盤輸入一行后回車的內容,內容也是"張三"。雖然我知道比較對象需要用equal,但是單說這個問題,為什么同樣是字符串比較,第二條從屏幕獲取的字符串"張三"跟"張三"比較,返回的是false呢?
我從目前學到的知識角度來分析的話,StuArr[i].SName和findName的hashcode都一樣,他們的地址應該是同樣的,那么應該返回ture。結果不是這樣子。
另外我還有一點猜測,會不會br.readLine()獲取的字符串在堆里,而SName成員變量在棧里,所以相比較之下會不同,但是這個怎么去驗證呢?
具體代碼如下:
import java.io.*;
import java.util.*;
class students
{
private String SName;
private int SAge;
private static students[] StuArr;
{
StuArr = new students[10];
}
//無參數構造器
students()
{
}
students(String sname,int sage)
{
this.SName = sname;
this.SAge = sage;
}
//SName的set和get方法
public void setSName(String sname)
{
this.SName = sname;
}
public String getSName()
{
System.out.println("姓名:" + this.SName);
return this.SName;
}
//SAge的set和get方法
public void setSAge(int sage)
{
this.SAge = sage;
}
public int getSAge()
{
System.out.println("年齡:" + this.SAge);
return this.SAge;
}
//將students對象保存進StuArr[]數組中。
public void setStuArr(students stu)
{
for (int i = 0;i<10 ;i++ )
{
if (StuArr[i] == null)
{
StuArr[i] = stu;
return;
}
}
System.out.println("當前數組成員已滿,添加失敗。");
}
public static void main(String[] args) throws Exception
{
students stu1 = new students();
//定義2個學生的值
stu1.setSName("張三");
stu1.setSAge(18);
students stu2 = new students("李四",19);
//將學生信息傳入StuArr數組
stu1.setStuArr(stu1);
stu2.setStuArr(stu2);
System.out.println("============================");
System.out.println("搜索名字:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String findName = null;
while ((findName=br.readLine()) != null)
{
for (int i = 0; i < 10 ;i++ )
{
if (StuArr[i] == null)
{
continue;
}
else
{
System.out.println(("張三"==findName));
if (StuArr[i].SName == findName)
{
System.out.println("搜索結果如下:");
System.out.println("姓名:"+StuArr[i].SName);
System.out.println("年齡:"+StuArr[i].SAge);
}
}
}
}
}
}
獲取屏幕的值與字符串相比較不相等,請問是什么原因?
慕碼人2483693
2019-01-16 19:27:46