简体   繁体   中英

How do I show two object are adjacent to each other?

I have to read in a file that shows one letter (City) is adjacent to the other. They are separated by a tab.

How do I show that Q is adjacent to X, R is adjacent to X (also), P is adjacent to R, etc etc...?

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

Segment of code to read in the file:

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);
    }

Method to that displays the names of all the cities which are adjacent to 'aCity'. @param aCity The city for which the adjacency list is desired.

    //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);
    //  }
    //}

}

您可以使用HashMap<City, HashSet<City>>结构,其中键是城市对象,并且指向其相邻城市的集合。

The easiest way would be:

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

This of course requires that the "City" class would need to implement the equals method and hence the hashcode method as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM