0

我必须阅读一个文件,显示一个字母(城市)与另一个相邻。它们由制表符分隔。

我如何证明 Q 与 X 相邻,R 与 X 相邻(也),P 与 R 相邻,等等……?

Q   X
R   X
P   R
P   W
W   S
S   T
T   W
W   Y
Y   R
Y   Z

要在文件中读取的代码段:

private ArrayList<City> cityList;
private ArrayList<City> cityFromList;
private ArrayList<City> cityToList;
Scanner theFlightFile = null;

    try {
        theFlightFile = new Scanner (new File("flightFile.txt"));
    }
    catch (Exception FileNotFoundException) {
        System.out.println(FileNotFoundException.getMessage());
    }
    while (theFlightFile.hasNext()) {
        String cityFrom = theFlightFile.next();
        String cityTo = theFlightFile.next();
        City cityA = new City(cityFrom);
        City cityB = new City(cityTo);

        cityToList.add(cityA);
        cityFromList.add(cityB);
        //testing input reading...
        System.out.println(cityFrom + " -----> " + cityTo);
    }

显示与“aCity”相邻的所有城市名称的方法。@param aCity 需要邻接列表的城市。

    //this is completely wrong, I know...
public void displayAdjacentCities(City aCity) {
    //for (aCity  : cityFromList) {
    //  for (City cityB : cityToList) {
    //      System.out.println(cityA + " is adjacent to " + cityB);
    //  }
    //}

}
4

2 回答 2

1

您可以使用一个HashMap<City, HashSet<City>>结构,其中键是一个城市对象,它指向一组相邻的城市。

于 2013-04-20T21:38:57.657 回答
0

最简单的方法是:

for (i = 0; i < cityFromList.length(); i++) {
  if (cityFromList.get(i).equals(aCity)) {
    System.out.println(aCity + " is adjacent to " + cityToList.get(i) + ".");
  }
}

这当然要求“City”类需要实现 equals 方法,因此也需要实现 hashcode 方法。

于 2013-04-20T21:41:59.260 回答