简体   繁体   中英

Why can't I instantiate new objects using a for loop, to fill an array?

I'm trying to make a tile map for a text based game, for my first Java project. When I try to use a for loop to add new objects(tiles) to each spot in the map, I get the error Type mismatch: cannot convert from Tile to Array . Where am I going wrong here?

public class helloworld {
    public static void main(String args[]) {
        
        world x = new world();
        Tile y = new Tile();
        System.out.println(y);
        
        for(int i = 0; i < x.tileGrid.length; i++) {
            for(int j = 0; j < x.tileGrid[i].length; j++) {
                x.tileGrid[i][j] = new Tile();
            }
        }
    }
}
import java.lang.reflect.Array;

public class world{
    Array tileGrid[][] = new Array[10][20];
    
    public static  void createWorld() {

    }
}
public class Tile {
    String tileType = "Grass";
    Boolean passable = true;
    
    @Override
    public String toString() {
        return tileType;
        
    }
}

You created array of arrays. It should be like this

public class world{
    Tile tileGrid[][] = new Tile[10][20];
    
    public static  void createWorld() {

    }
}

Please do not name classes with small letter. They should always start with capital letter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM