加载平铺贴图时Java索引超出界限异常

时间:2014-04-28 05:35:50

标签: java save loading multidimensional-array indexoutofboundsexception

在我正在制作的工具中,我需要能够加载并保存瓷砖地图并进行编辑。当我单击鼠标时,它将更改鼠标悬停在我选择的图块上的当前图块。出于某种原因,每当我点击任何图块时,第一个图块总是变为某种奇怪的黑色,并且抛出一个超出范围的索引。它说"线程中的异常" AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException:1     在Engine.Map.loadUpdatedMap(Map.java:161)     在Engine.Pane.mousePressed(Pane.java:65)。我检查了文本文件,并将其替换为当前的图块大小(当它应为0时)。代码发布如下,任何想法?

这是发生错误的地方(Map.java)

public void loadUpdatedMap(){
        try {
            BufferedReader reader = new BufferedReader(new FileReader(new File(fileName + ".txt")));

            for (int i = 0; i < mapHeight; i++){
                String read = reader.readLine();
                String[] skips = read.split(" ");
                for (int j = 0; j < mapWidth; j++){
                    map[i][j] = Byte.parseByte(skips[j]);
                }
            }

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

这是我替换瓷砖(Pane.java)

的方式
public void mousePressed(MouseEvent e) {
    if (map.created && map.tileSize != 0){
        currentX = e.getX() / map.tileSize;
        if (e.getY() / map.tileSize > 1){
            currentY = (e.getY() - map.tileSize) / map.tileSize;
        }
        else{
            currentY = (e.getY() / map.tileSize);
        }
        map.setTile(currentX, currentY, currentSelection);
        map.loadUpdatedMap();
    }
}

用于保存地图的代码

public void saveToLocation(){
    try{
        if (fileName == null){
            fileName = "default";
        }
        FileOutputStream fout = new FileOutputStream(new File(System.getProperty("user.dir"), fileName + ".txt"));
        System.out.println("File was saved to: " + new File(System.getProperty("user.dir"), fileName + ".txt"));
        fout.write(String.valueOf(tileSize).getBytes());
        fout.write(System.getProperty("line.separator").getBytes());
        fout.write(String.valueOf(mapWidth).getBytes());
        fout.write(System.getProperty("line.separator").getBytes());
        fout.write(String.valueOf(mapHeight).getBytes());
        fout.write(System.getProperty("line.separator").getBytes());

        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map[i].length; j++) {
                fout.write(String.valueOf(map[i][j]).getBytes());
                fout.write(String.valueOf(" ").getBytes());
            }
            fout.write(System.getProperty("line.separator").getBytes());
        }
        fout.close();
    }catch (Exception e){
        e.printStackTrace();
    }

}

点击任何内容之前

Before Clicks

首次点击后

After Click

文本文件结果

After Click

1 个答案:

答案 0 :(得分:0)

之后你的ships数组有多大
 String[] skips = read.split(" ");

根据你的代码,它是mapWidth,然后你试图从数组中提取那么多元素。

也许

for (int j = 0; j < skips.length; j++){

会更正确