编辑:这个答案可能看起来已经过时了,因为 OP 决定编辑这个问题,在这个过程中删除了他的代码。
您的代码中有 2 个错误:
- 您的内部类
Station 不是静态的,这意味着您不能在静态上下文中实例化它。这会产生您看到的错误消息。
- 您认为 Java 是按引用传递的,并试图覆盖变量指向的值(在 Java 中您不能这样做)。
您可以通过将 Station-class 设为静态 (static class Station) 并通过使工作站使用类变量并使用它们的字段创建字符串来纠正错误。
您还可以为 Station-class 实现一个 getInfo()-method,它自己准备其信息。有了这个,你可以打电话给System.out.println(STATION_YOU_WANT.getInfo())。
我花了一些时间为这个问题写了一个带注释的解决方案。
其中最令人困惑的部分可能是varargs 的使用(下面代码中的String...)。它们基本上允许您将任意数量的参数传递给方法,该方法本质上会被 Java 转换为数组。
import java.util.HashMap;
import java.util.Locale;
import java.util.Scanner;
public class StationInformation {
private static class Station {
private String name;
private int distanceToPlatform;
private boolean stepFree;
private String[] alternateNames;
Station(String name, int distanceToPlatform, boolean stepFree, String...alternateNames) {
this.name = name;
this.distanceToPlatform = distanceToPlatform;
this.stepFree = stepFree;
this.alternateNames = alternateNames; // 'String...' makes that parameter optional, resulting in 'null' if no value is passed
}
String getInfo() {
return name + " does" + (stepFree ? " " : " not ")
+ "have step free access.\nIt is " + distanceToPlatform + "m from entrance to platform.";
}
}
private static HashMap<String, Station> stations = new HashMap<String, Station>();
public static void main(String[] args) {
createStations();
// The Program
Scanner scanner = new Scanner(System.in);
// Keep requesting input until receiving a valid number
int num;
for (;;) { // 'for (;;) ...' is effectively the same as 'while (true) ...'
System.out.print("How many stations do you need to know about? ");
String input = scanner.nextLine();
try {
num = Integer.parseInt(input);
break;
} catch (Exception exc) {
// Do nothing
}
System.out.println("Please enter a correct number.");
}
for (int i = 0; i < num; ++i) {
System.out.print("\nWhat station do you need to know about? ");
String input = scanner.nextLine();
// If available, show Station-information
if (stations.containsKey(input.toLowerCase(Locale.ROOT))) {
System.out.println(stations.get(input.toLowerCase(Locale.ROOT)).getInfo());
} else {
System.out.println("\"" + input + "\" is not a London Underground Station.");
}
}
scanner.close(); // Close Scanner; Here actually not needed because program will be closed right after, freeing its resources anyway
}
private static void createStations() {
// Add new Stations here to automatically add them to the HashMap
Station[] stations = new Station[] {
new Station("Stepney Green", 100, false),
new Station("King's Cross", 700, true, "Kings Cross"),
new Station("Oxford Circus", 200, true)
};
for (Station station : stations) {
StationInformation.stations.put(station.name.toLowerCase(Locale.ROOT), station);
// Alternative names will be mapped to the same Station
if (station.alternateNames == null) continue;
for (String altName : station.alternateNames)
StationInformation.stations.put(altName.toLowerCase(Locale.ROOT), station);
}
}
}