This question already has answers here:
How do I compare strings in Java?
(23个答案)
6年前关闭。
这是我的程序
我的文本文件如下所示:
我的驱动程序类的输出是:
这就是我想要的样子
这就是问题所在
“ currentSchool”变量永远不会改变,我也不知道为什么! “ *”被视为学生(我想将其用作定界符,即程序在遇到它时将忽略它)。取而代之的是,“ if line = *”命令被完全忽略,因此,学校永远不会改变,并且学生的书写方式不正确。
不要使用“ ==”来比较对象。
使用
(23个答案)
6年前关闭。
这是我的程序
String thisSchool=buffer.readLine();
String thisLine;
while((thisLine = buffer.readLine()) != null){
if(thisLine=="*")
{
thisSchool=buffer.readLine();
}
else
{
School school = new School(thisSchool);
Student student = new Student(thisLine, school);
StudentList.add(student);
}
}
我的文本文件如下所示:
School1
A
B
C
*
School2
D
E
*
School3
F
我的驱动程序类的输出是:
A School1
B School1
C School1
* School1
School2 School1
D School1
E School1
* School1
School3 School1
F School1
这就是我想要的样子
A School1
B School1
C School1
D School2
E School2
F School3
这就是问题所在
“ currentSchool”变量永远不会改变,我也不知道为什么! “ *”被视为学生(我想将其用作定界符,即程序在遇到它时将忽略它)。取而代之的是,“ if line = *”命令被完全忽略,因此,学校永远不会改变,并且学生的书写方式不正确。
最佳答案
if(thisLine=="*")
不要使用“ ==”来比较对象。
使用
equals()
方法:if(thisLine.equals("*"))