Sets entire map to one tile.


int[][] map = {
				{1,1,2,2,2,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{1,2,2,2,2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{1,1,2,2,2,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{1,1,1,2,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
				{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
		};
		
		int mapWidth = 20;
		int mapHeight = 15;
		
		File file = new File("maps/map1.txt");
		Scanner sc;

		for(int x = 0; x < mapWidth; x++) {
			for(int y = 0; y < mapHeight; y++) {
				try {
					sc = new Scanner(file);
					while(sc.hasNextLine()) {
						String i = sc.nextLine();
						map[y][x] = Integer.parseInt(i);
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		}

This code is supposed to load the tile id’s from a text file. Which it does. The String i is actually set to each individual number in the text file. Then, at the end of the file the map gets set to the entire map of only the last id. Why is that? I tried to trouble shoot it and figure it out but I couldn’t. What do you guys think?

I’m not quite sure what the problem is as your description is pretty vague, but whatever it is, you shouldn’t be creating a new Scanner for each tile. Use 1 Scanner, don’t forget to close() it when done.

Ah that could be that problem. And the glitch is that the entire map is set to the last integer in the text file instead of its corresponding tile on the screen.

Yep, because the while() loop is just setting the same tile to every value in the file, so the last one is what it winds up as, and it happens for every tile (the outer loop).

Just do this:


try(Scanner s = new Scanner(file)) {
    for(int x=0;x<width;x++) {
        for(int y=0;i<height;y++) {
            map[y][x] = s.nextInt();
        }
    }
}

try-with-resources to auto close Scanner when done or in case of error.

Also btw, indexing an array like [y][x] is good, but not in a loop with x on the outside. The loops should be nested like the array dimensions.

Thanks a lot! One more question:

Anyway to make a dynamic 2D array so that I am not confined to a strict map size for all my maps?

List<List> or List<List>

That lets you expand in positive directions, if you want it to be expandable in all directions you could take a HashMap approach: [icode]Map<Point, Tile> map;[/icode]

This also has the benefit that you don’t have to have a rectangular map, and can have “islands” of tiles without having to enclose the entire world in a rectangle.