hotelListに5つ以上の値を指定して以下のコードを実行しようとすると、次のエラーが発生します。私はペナルティとパスを反復する方法にはエラーがあると思うが、それを修正する方法は不明だ。スレッド "メイン" java.lang.ArrayIndexOutOfBoundsExceptionでforループ内のリストに値を追加するとエラーが発生する
例外: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();
}
あなたが 'penalties [j]'と言うとき、 'j'が' penalties'の長さより大きい場合、あなたが記述するエラーが発生します。 'i'が' hotelList.length'よりも小さいかどうかをチェックしていることに注意してください(ただし、 'penalties'と' path'も同様にインデックスに使用します)。そして 'hotelList'は' 6'要素を持っています... –