[英]Splitting a string array gives me array index out of bounds
好的,我正在嘗試使用此代碼生成切片地圖。 但是,我繼續使數組索引超出范圍。 因此,這是如何在文本文件中添加“路徑”的。 它擁有不同的數字,每個數字代表自己的瓷磚紋理。 文本文件的前2個數字是我們使用的寬度和高度。 此for循環正在執行的操作是將tile [x] [y]的每個數組分配給其所屬位置中的tile。 這是我正在使用的文本文件:
15 5
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
(idk行之間沒有多余的空格,為什么這樣做)
如果有什么需要清理的,請告訴我
String textFile = TextUtility.loadTextAsString(path);
String[] tileValue = textFile.split("\\s+");
width = TextUtility.parseToInt(tileValue[0]);
height = TextUtility.parseToInt(tileValue[1]);
System.out.println(width+" "+height + " " + tileValue.length);
tiles = new int[width][height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
tiles[x][y] = TextUtility.parseToInt(tileValue[(x+y*(width))+2]);
System.out.print(""+ tileValue[(x+ y*(width))+2]);
}
}
IndexOutOfBounds
是由於(x+ y*(width))+2
表達式引起的。 但是,如果您只是試圖將每個tile的值保存在tile[][]
,則有一種更簡單的方法可以完成它!
我假設您的loadTextAsString(path)
有點像這樣:
public static String loadTextAsString(String path) {
StringBuilder builder = new StringBuilder();
try (BufferedReader fileReader = Files.newBufferedReader(Paths.get(path))) {
String eachLine = "";
while ((eachLine = fileReader.readLine()) != null) {
builder.append(eachLine);
builder.append(System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
這將返回文件的文本表示,如以下示例所示:
15 5
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
現在,讓我們從將所有這些值放入二維數組的實際方法開始。
public int[][] createTiles(String path){
String textFile = loadTextAsString(path);
//Get all individual lines in an array
String[] allLinesInFile = textFile.split("\\n|\\r");
int width = Integer.parseInt(allLinesInFile[0].split("\\s")[0]);
int height = Integer.parseInt(allLinesInFile[0].split("\\s")[1]);
System.out.println("Width -> " + width);
System.out.println("Height -> " + height);
//2-D array to hold the tiles
int[][] tiles = new int[height][width];
//Row count for the array
int row = 0;
for(String eachLine : allLinesInFile){
String[] allTiles = eachLine.split("\\s");
/*
* This will ignore the very first line of the file with width and
* height and new line characters
*
*/
if(allTiles.length != width){
continue;
}
//Column count for the array
int col = 0;
for(String eachTile : allTiles){
tiles[row][col] = Integer.parseInt(eachTile);
// Increment column
col++;
}
// Increment Row
row++;
}
//Return the 2-D array.
return tiles;
}
我希望這是您想要實現的目標。
注意:我希望您的TextUtility.parseToInt(String val)
方法等效於Integer.parseInt(String val)
,因此我在后面使用了。
您輸入的高度為5,但只有4行圖塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.