数组越界异常,不明显在哪里

时间:2016-03-06 05:52:11

标签: java arrays indexing indexoutofboundsexception

我在尝试填充我创建的数组时遇到了麻烦。似乎无论我如何设置循环它仍然抛出错误。看着我的代码,我看不出哪里出错,有人能给我一个线索吗?

 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();       
    }   
}

1 个答案:

答案 0 :(得分:0)

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

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

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

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