向for循环中的列表添加更多值时收到错误

时间:2017-05-20 17:33:48

标签: java

每当我尝试在hotelList中运行超过5个值的以下代码时,我一直收到以下错误。我认为迭代惩罚和路径的方式存在错误,但我不确定如何修复它。

线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:5     在First.main(First.java:81)

import java.util.*;
import java.io.*;

class First {


    public static void printPath(int path[], int i) {
        if (i == 0) return;
        printPath(path, path[i]);
        System.out.print(i + " ");
    }


    public static void main(String[] args) throws FileNotFoundException, java.io.IOException {

        Scanner dataFile = new Scanner(new File("C:\\Users\\USER\\Documents\\Data.txt"));
        ArrayList<Integer> hotels = new ArrayList<>();
        hotels.add(0);
        while (dataFile.hasNextLine()) {
            hotels.add(dataFile.nextInt());
        }
        dataFile.close();
        //optimalStops(hotels);


        //int[] hotelList = new int[hotels.size()];

        /*for (int i = 0; i < hotels.size(); i++) {
            if (hotels.get(i) != null) {
                hotelList[i] = hotels.get(i);
            }*/

            int hotelList[] = {0, 66, 83, 130, 180, 1};
            int penalties[] = {0, (int) Math.pow(200 - hotelList[1], 2), -1, -1, -1};
            int path[] = {0, 0, -1, -1, -1};
            for (int i = 2; i <= hotelList.length - 1; i++) {
                for (int j = 0; j < i; j++) {
                    int tempPen = (int) (penalties[j] + Math.pow(200 - (hotelList[i] - hotelList[j]), 2));
                    if (penalties[i] == -1 || tempPen < penalties[i]) {
                        penalties[i] = tempPen;
                        path[i] = j;
                    }
                }
            }
            for (int i = 1; i < hotelList.length; i++) {
                System.out.print("Hotel: " + hotelList[i] + ", penalty: " + penalties[i] + ", path: ");
                printPath(path, i);
                System.out.println();
            }

1 个答案:

答案 0 :(得分:0)

你的处罚只有5个项目。所以当你这样称呼时:

for (int i = 1; i < hotelList.length; i++) {
    System.out.print("Hotel: " + hotelList[i] + ", penalty: " + penalties[i] + ", path: ");

你正试图访问惩罚[5],这会引发越界错误。

在此部分代码中也存在同样的问题:

for (int i = 2; i <= hotelList.length - 1; i++) {
    for (int j = 0; j < i; j++) {
    int tempPen = (int) (penalties[j] + Math.pow(200 - (hotelList[i] - hotelList[j]), 2));
    if (penalties[i] == -1 || tempPen < penalties[i]) {
        penalties[i] = tempPen;
        path[i] = j;
    } 
} 

我认为你的意图是做更多这样的事情:

for (int i = 1; i < hotelList.length; i++) {
    for(int j = 0; j < penalties.length; j++){
        System.out.print("Hotel: " + hotelList[i] + ", penalty: " + penalties[j] + ", path: ");

我无法告诉你对另一个循环的意图。如果你能解释一下你想要完成什么,我可能会帮忙。