【问题标题】:Array out of bounds exception, not evident where数组越界异常,在哪里不明显
【发布时间】:2016-06-19 19:36:37
【问题描述】:

我在尝试填充我创建的数组时遇到了问题。似乎无论我如何设置循环它仍然抛出错误。查看我的代码,我看不出哪里出错了,有人能给我提示吗?

 import java.io.File;
 import java.io.FileNotFoundException;
 import java.util.Scanner;

   /*************************************************************************
  * Name        :  
* Username    : 
 * Description :  
 *************************************************************************/



    public class World{

    String fileName;
    Tile[][] map;
    int width,height;
    int x_coor, y_coor;

public World(String inFileName){
    this.fileName = inFileName;

    //Create all the tiles

    try {

        //create the scanner in order to read the file parameters
        Scanner scanner = new Scanner(new File(fileName));
        //Get the height and width of the map
        int height, width;
        width = scanner.nextInt();
        height  = scanner.nextInt();
        Tile[][] map = new Tile[width][height];
        //testing
        System.out.println("Width is: " +width);
        System.out.println("Height is: " + height);
        //create blank map
        for(int i = 0; i < height-1; i++){
            for(int j = 0; j < width -1; j++){
                map[i][j] = new Tile("Blank");
                System.out.println("System created point:" + i + j);
            }
        }

        //instantiate the map, and fill it
        for(int i = 0; i < height ; i++){
            for(int j = 0; j < width - 1; j++){
                //Testing code
                System.out.print(j);
                //create tiles
                map[i][j] = new Tile(scanner.next());
            }
            //Testing code
            System.out.println();
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

   }
         private void draw(){

    }

    public static void main(String [] args)
    {       


        World world = new World(args[0]);
        world.draw();       
    }   
}

【问题讨论】:

  • 请提供您遇到的错误

标签: java arrays indexing indexoutofboundsexception


【解决方案1】:

for(int i = 0; i &lt; height ; i++) 中的第二个嵌套 for 循环 (//instantiate the map, and fill it) 中,您没有在 1 中减少 height

for(int i = 0 ; i < height - 1 ; i++)

此外,您在Tile[][] map = new Tile[width][height]; 中混合了widthheight。应该是

Tile[][] map = new Tile[height][width];

【讨论】:

  • 修复后仍然在 map[i][j] = new Tile("Blank");
  • @Kevin 你还有问题吗?
  • @Kevin 我发现了问题。检查编辑的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 2019-07-18
  • 1970-01-01
相关资源
最近更新 更多