我正在试着用Dijkstra算法找出最短路径。但是我的代码在Main.main(Main.java:17)显示了“线程中的异常"main”java.lang.ArrayIndexOutOfBoundsException:索引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]);
}
发布于 2020-11-05 19:14:40
您可以从异常消息中获得线索,
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
。Java中的数组以0
索引开头。因此,您可能应该改用array[i] = Integer.parseInt(str[1]) - Integer.parseInt(str[0]);
。
发布于 2020-11-05 19:34:45
在从str数组中获取值之前添加check,如下所示-
if (str.size() > 2){
array[i] = Integer.parseInt(str[2]) - Integer.parseInt(str[1]);
if (array[i] < 0) {
array[i] *= (-1);
}
i++;
}
https://stackoverflow.com/questions/64695375
复制相似问题