编译器无法识别类字符串值等于另一个字符串值


public class Station {
String name;
boolean pass;
int distance;
// method to create a new Station taking the arguments of the name,pass and distance in the parameter
public static Station createStation(String name, boolean pass, int distance) {  
}
// Array list containing all the Stations in London we will use
static Station[] StationList = {createStation("Stepney Green", false, 100), createStation("Kings Cross", true, 700), createStation(
"Oxford Circus", true, 200)};
public static String infoAboutStation(Station station) {
String message;
if (station.pass)
message = //string message
else
message = //string message
return message;
}
public static String checkInfo(String stationName){
String info = null;
for(Station station : StationList){     
if(stationName == station.name) { //it does not recognise it to be the same for some reason
info = stationName + infoAboutStation(station);
}
else
info = stationName + " message ";
}
return info;
}
public static void printInfo(){
Scanner scanner = new Scanner(System.in);
System.out.println("How many... ");
int totalResponses = Integer.parseInt(scanner.nextLine());
String choice;
for(int i = 0; i < totalResponses; ++i){
System.out.println("Enter a station: ");
choice = scanner.nextLine();
System.out.println(checkInfo(choice));
}
}
// psvm(String[] args)
}

因此程序运行良好,但当我们使用";Stepney Green"Kings Cross"牛津马戏团;作为checkinfo(choice)的选择输入,它不认为它与方法checkInfo(stationName //choice)中的stationName == station.name相同

Intellij调试器在stationName == station.name上读取此内容

-StationList={Station[3]@980}->0={Station@994}1={Station@997}2={Station@998}

-静态->StationList={Station[3]@980}

-stationName=";Stepney Green"value={byte[13]@996}编码器=0 hash=0 hashsZero=0

-info=空

-工作站={Station@994}->name=";Stepney Green";,通过=错误,距离=100

-station.name=";Stepney Green&quot-&gt;value={byte[13]@999]rest为零

声明旁边写着stationName:";Stepney Green"电台:Station@994.它不是打印出stationName+infoAboutStation,而是转到另一个站并打印";Stepney Green不是伦敦地铁站;。我很困惑为什么。另外,如果你不介意帮助我让这个代码变得更高效、更好的话。

您应该使用equals()比较String
替换此

if(stationName == station.name)

通过

if(stationName.equals(station.name))

固定更改为

for(Station station : StationList){
if(stationName.equals(station.name)) {
info = stationName + infoAboutStation(station);
break;
}
}

感谢的帮助

相关内容

  • 没有找到相关文章

最新更新