【发布时间】:2020-09-27 18:45:11
【问题描述】:
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”、“Oxford Circus”作为checkinfo(choice) 的选择输入时,它不认为它与stationName == station.name 相同方法checkInfo(stationName //choice)
Intellij 调试器在 stationName == station.name 读取此内容
-StationList = {Station[3]@980} -> 0 = {Station@994} 1 = {Station@997} 2 = {Station@998}
-静态-> StationList = {Station[3]@980}
-stationName = "Stepney Green" 值 = {byte[13]@996} 编码器 = 0 hash = 0 hashisZero = 0
-info = null
-station = {Station@994} -> name = "Stepney Green", pass = false, distance = 100
-station.name = "Stepney Green" -> value = {byte[13]@999] 剩余为零
在声明旁边,它写着站名:“Stepney Green”站:Station@994。它没有打印出 stationName + infoAboutStation,而是转到 else 站并打印“Stepney Green is not a London Underground Station”。我很困惑为什么。另外,如果您不介意帮助我使这段代码更高效、更好。
【问题讨论】:
-
不要将字符串与
==进行比较 - 比较stationName和station.name引用相同的字符串对象。由于一个是编译时间常数,另一个是从扫描仪读取的值,因此它们不是同一个字符串对象。而是使用stationName.equals(station.Name) -
@ThomasKläger 不,它现在只适用于牛津马戏团,但不适用于其他两个
标签: java arrays if-statement debugging compare