[英]ArrayIndexOutOfBoundsException in Dijkstra's shortest path algorithm
我正在尝试使用 Dijkstra 算法找出最短路径。 但我的代码显示“线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:在Main.main(Main.java:17)处索引2超出长度1的范围
public static void main(String args[]) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter input file name: ");
String file = scanner.nextLine();
BufferedReader br = new BufferedReader(new FileReader(file));
String s;
int array[] = new int[120];
int count = 0;
int i = 0;
while ((s = br.readLine()) != null) {
if (count > 0 && count < 121) {
String str[] = s.split(" ");
array[i] = Integer.parseInt(str[2]) - Integer.parseInt(str[1]);
if (array[i] < 0) {
array[i] *= (-1);
}
i++;
}
count++;
}
int temp;
for (int j = 0; j < array.length; j++) {
System.out.println(array[j]);
}
for (int j = 0; j < array.length; j++) {
System.out.println(array[j]);
for (int k = j + 1; k < array.length; k++) {
if (array[j] > array[k]) {
temp = array[j];
array[j] = array[k];
array[k] = temp;
}
}
}
System.out.println("Shortest path: " + array[0]);
System.out.println("Second Shortest path: " + array[1]);
}
你从异常消息中得到一个线索,
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 1 at Main.main(Main.java:17)
由于代码格式较早,我假设line 17
是array[i] = Integer.parseInt(str[2]) - Integer.parseInt(str[1]);
. 在这种情况下str[2]
具有Index 2
并且超出范围。 str
的length 1
可能length 1
具体取决于您提供的输入。 Java 中的数组从0
索引开始。 所以你可能应该使用array[i] = Integer.parseInt(str[1]) - Integer.parseInt(str[0]);
反而。
在从 str 数组中获取值之前添加检查,如下所示 -
if (str.size() > 2){
array[i] = Integer.parseInt(str[2]) - Integer.parseInt(str[1]);
if (array[i] < 0) {
array[i] *= (-1);
}
i++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.