gpt4 book ai didi

java - Jar 出现数组跳出异常,但 Eclipse 没有

转载 作者:行者123 更新时间:2023-12-01 11:24:39 24 4
gpt4 key购买 nike

当我转换我的 Java 时项目到 Jar 文件中,ArrayIndexOutOfBounds -2 异常出现在这一段代码的第 3 行:

for (int i = 0; i < copy.get(copy.size() - 2).size(); i++) {
if (!copy.get(copy.size() - 2).get(i).toString().equals(" ")) {
startLocations[index] = Integer.parseInt(copy.get(copy.size() - 2).get(i).toString());
index++;
}
}

我觉得这很奇怪,因为程序在 Eclipse 中运行得很好,并且 copy 的大小,一个2D ArrayList暂时保留迷宫的网格是 9。当我将其转换为 Jar 并从 cmd 运行它时,代码失败。下面是完整的相关代码。所有文件都位于正确的位置。

String fileName = "maze.txt";
String line = null;
ArrayList < ArrayList < Square >> grid = new ArrayList < ArrayList < Square >> ();

try {
// Setup FileReader, BufferedReader, and LineReader
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);

int row = 0;

// Get all the lines inside the maze file
while ((line = bufferedReader.readLine()) != null) {
ArrayList < Square > lineList = new ArrayList < Square > ();

for (int i = 0; i < line.length(); i++) {
String letter = Character.toString(line.charAt(i));

if (letter.equals("L")) {
lineList.add(new LockedSquare(row, i, letter));
} else {
lineList.add(new Square(row, i, letter));
}

row++;
}

grid.add(lineList);
}

// Cut down grid to only the maze

ArrayList < ArrayList < Square >> copy = grid;

int length = grid.size();

grid = new ArrayList < ArrayList < Square >> ();

for (int i = 0; i < length - 2; i++) {
grid.add(copy.get(i));
}

// Start position

int[] startLocations = new int[2];

int index = 0;

for (int i = 0; i < copy.get(copy.size() - 2).size(); i++) {
if (!copy.get(copy.size() - 2).get(i).toString().equals(" ")) {
startLocations[index] = Integer.parseInt(copy.get(copy.size() - 2).get(i).toString());
index++;
}
}

int playerX = startLocations[0];
int playerY = startLocations[1];
}
// Exceptions
catch (FileNotFoundException e) {
System.out.println("Error: maze.txt not found");
} catch (IOException ex) {
System.out.println("Error reading maze.txt");
}

最佳答案

发生这种情况是因为您的 jar 文件无法找到 maze.txt .

更改String fileName = "maze.txt";String fileName = <absolute-path-for-maze.txt> ;它应该通过 jar

关于java - Jar 出现数组跳出异常,但 Eclipse 没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30928975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com