我试图通过链表显示两个对象之间的邻接关系。当我试图打印出邻接时,它会跳过第一行。打印出来的是:
X
X
R >>> W
S >>> Y
T
W
R >>> Z
它应该是:
Q >>> X
R >>> x
P >>> R >>> W
W >>> S >>> Y
S >>> T
T >>> W
Y >>> R >>> Z
正如您所看到的,只打印出第二级和第三级,而不是所有级别。
相关代码:
public static void main(String[] args) throws FileNotFoundException {
FlightMap flights = new FlightMap();
flights.loadFlightMap("cityFile.txt", "flightFile.txt");
Scanner requestInStream = null;
requestInStream = new Scanner(new File("requestFile.txt"));
//DEBUGGING
String[] str = new String[] {"Q", "X", "R", "P", "W", "S", "T", "Y", "Z"};
String temp = null;
for ( int x = 0; x < str.length; x++) {
temp = str[x];
City city = new City(temp);
flights.displayAdjacentCities(city);
}
FlightMap类
//Read in the files from the main...
private int size = 0;
private City[] allCities;
private LinkedList<City>[] adjacents;
public FlightMap() {
}
@SuppressWarnings("unchecked")
public void loadFlightMap(String cityFileName, String flightFileName)
throws FileNotFoundException {
Scanner inStream = null;
inStream = new Scanner(new File(cityFileName));
while(inStream.hasNextLine()) {
size++;
inStream.nextLine();
}
inStream.close();
allCities = new City[size];
adjacents = (LinkedList<City>[]) new LinkedList[size];
for(int x = 0; x < size; x++) {
adjacents[x] = new LinkedList<City>();
}
Scanner inStream1 = null;
inStream1 = new Scanner (new File(cityFileName));
for(int x = 0; x <size; x++) {
String input = inStream1.nextLine();
allCities[x] = new City (input);
}
inStream1 = new Scanner (new File(flightFileName));
String data;
while (inStream1.hasNext()) {
int flag = 0;
data = inStream1.next();
for (int i = 0; i < size && flag !=1; i++) {
if(allCities[i].getName().equalsIgnoreCase(data)) {
data = inStream1.next();
for (int j = 0; j < size; j++) {
if (allCities[j].getName().equalsIgnoreCase(data)) {
adjacents[i].add(allCities[j]);
flag = 1;
}
}
}
}
}
inStream1.close();
}
显示邻接方法:
public void displayAdjacentCities(City aCity) {
for(int x = 0; x < size; x++) {
if (aCity.getName().equalsIgnoreCase(allCities[x].getName())) {
Iterator<City> iter = adjacents[x].iterator();
while(iter.hasNext()) {
System.out.print(iter.next().getName());
if(iter.hasNext()) {
System.out.print(" >>> ");
}
}
System.out.println("\n");
}
}
所有对象都在cityFile中: (每个单独一行)
Q
X
R
P
W
S
T
Y
Z
邻接在flightFile中(由两个字母之间的标签分隔,另一对分开:
Q X
R X
P R
P W
W S
S T
T W
W Y
Y R
Y Z
所需的路径在requestFile中:
Q X
P X
P T
P Z
P X
P Q
T P
A S
R X
T X
Q X
我不确定我是否在问正确的问题。
答案 0 :(得分:0)
示例答案看起来好像一个城市应该被认为与自身相邻? 试试这个:
public void displayAdjacentCities(City aCity) {
for(int x = 0; x < size; x++) {
if (aCity.getName().equalsIgnoreCase(allCities[x].getName())) {
if (adjacents[x].size() == 0) continue;
System.out.print(aCity.getName());
for (City other : adjacents[x]) {
System.out.print(" >>> " + other.getName());
}
System.out.println();
}
}
}