我收到此錯誤,需要幫助。代碼讀入 .txt 檔案并給出輸出。我相信這應該是一個簡單的修復,但我無法找到解決方案。第一個標記代表地牢中房間的名稱。之后,每對令牌代表一個連接的房間以及前往該房間所需的步驟。(一個房間最多可以連接到 32 個其他房間)。如果一個房間在輸入檔案中沒有條目,這意味著它沒有任何出路。每個地牢入口都命名為A。當有多個連通房間時,應按字母順序進行探索。標有 X 的房間包含一個心臟容器。并非所有房間都是相連的。輸入:
A B 25 G 11 I 7
B C 10 E 12
C E 1 H 25 L 88
D A 51 J 2 N 48
E A 99 B 23 K 3
F C 23 D 3 E 75
G A 12 D 29 X 9
H G 1 C 2 M 10
I E 7 B 2 A 9
J I 12 H 11 G 13 F 27 D 85
K A 12 B 13
L E 70 G 50 J 20 K 1 B 4
M L 10 A 11 F 91 H 67 N 92
N M 1
輸出:所需藥水數量:0 到胸部的距離:20 到胸部的路徑:AGX
代碼:
class GraphEdge {
private char from;
private char to;
private int weight;
public GraphEdge(char from, char to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
public class Graph {
public static void main(String[] args) throws FileNotFoundException {
DFS();}
private static void DFS()
char source = 'A';// source vertex
char destination = 'X';// destination vertex
ArrayList<GraphEdge> edges = new ArrayList<GraphEdge>();// list to hold all edges
HashSet<Character> uniqueVertices = new HashSet<Character>();// all unique vertices in map
ArrayList<Character> allVertices = new ArrayList<Character>();// list to hold all vertices
// System.out.println("Input File:");
while (obj.hasNextLine()) {// while input file has lines left
String line = obj.nextLine();
System.out.println(line);
String vertex[] = line.split(" ");// split the line into source vertex, destination vertex and the weight
int i = 1;
while (i < vertex.length) {
GraphEdge edge = new GraphEdge(vertex[0].charAt(0), vertex[i].charAt(0),Integer.parseInt(vertex[i 1]));
edges.add(edge);
i = i 2;
System.out.println(edge);
System.out.println(vertex[0].charAt(0));
System.out.println(vertex[1].charAt(0));
//System.out.println(vertex[i].charAt(0));
if (!uniqueVertices.contains(vertex[0].charAt(0))) {// if vertex not present in unique vertices map, add it
// in map and arraylist
uniqueVertices.add(vertex[0].charAt(0));
allVertices.add(vertex[0].charAt(0));
System.out.println(allVertices);
}
if (!uniqueVertices.contains(vertex[1].charAt(0))) {// if vertex not present in unique vertices map, add it
// in map and arraylist
uniqueVertices.add(vertex[1].charAt(0));
allVertices.add(vertex[1].charAt(0));
System.out.println(allVertices);
}
if (!uniqueVertices.contains(vertex[i].charAt(0))) {// if vertex not present in unique vertices map, add it
// in map and arraylist
uniqueVertices.add(vertex[i].charAt(0));
allVertices.add(vertex[i].charAt(0));
System.out.println(allVertices);
}
}
}
uj5u.com熱心網友回復:
索引變數i增加2,因此最后一個if塊嘗試在最后一個索引之前訪問。您需要break在最后一個if塊之前向回圈添加一些保護代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/379804.html
