简体   繁体   English

Dijkstra 最短路径算法中的 ArrayIndexOutOfBoundsException

[英]ArrayIndexOutOfBoundsException in Dijkstra's shortest path algorithm

I am trying to find out shortest path using Dijkstra's algorithm.我正在尝试使用 Dijkstra 算法找出最短路径。 but my code is showing "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 1 at Main.main(Main.java:17)但我的代码显示“线程“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]);
}

You get a clue from the exception message,你从异常消息中得到一个线索,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 1 at Main.main(Main.java:17)

Since the code was formatted earlier, am assuming line 17 is array[i] = Integer.parseInt(str[2]) - Integer.parseInt(str[1]);由于代码格式较早,我假设line 17array[i] = Integer.parseInt(str[2]) - Integer.parseInt(str[1]); . . In which case str[2] has Index 2 and is out of bounds.在这种情况下str[2]具有Index 2并且超出范围。 str is probably length 1 depending on the input you gave. strlength 1可能length 1具体取决于您提供的输入。 Arrays in Java start with 0 index. Java 中的数组从0索引开始。 So you probably should use array[i] = Integer.parseInt(str[1]) - Integer.parseInt(str[0]);所以你可能应该使用array[i] = Integer.parseInt(str[1]) - Integer.parseInt(str[0]); instead.反而。

Add check before getting the values from the str array as below -在从 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.

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