【问题标题】:tiled map in java from array来自数组的java中的平铺地图
【发布时间】:2014-07-07 07:10:46
【问题描述】:

我正在尝试遍历整数的二维数组以使用 Java 的 Graphics2D 生成平铺地图。

    int[][] mapArray = {{1, 1, 1, 1, 1, 1, 1, 1},
                    {1, 0, 0, 0, 0, 0, 0, 1},
                    {1, 0, 0, 0, 0, 0, 0, 1},
                    {1, 0, 0, 0, 0, 0, 0, 1},
                    {1, 0, 0, 0, 0, 0, 0, 1},
                    {1, 1, 1, 1, 1, 1, 1, 1}};

    public void draw(Graphics2D g2d){
    for(int y = 0; y < mapArray.length; y++){
        for(int x = 0; x < mapArray[0].length; x++){
            if(mapArray[x][y] == 1){
                 ImageIcon ic = new ImageIcon("/Textures/stone.jpg");
                 g2d.drawImage(ic.getImage(), x, y, null);
            }
            else if(mapArray[x][y] == 0){
                 ImageIcon ic = new ImageIcon("/Textures/water.jpg");
                 g2d.drawImage(ic.getImage(), x, y, null);
            }

我似乎无法理解迭代二维数组的逻辑。理想情况下,每个 0 代表一个水瓦,每个 1 代表一个石瓦。每次我运行这个我都会得到一个NullPointerException

【问题讨论】:

  • NPE 来自哪里?
  • 这里的 NPE 代表什么?
  • @KickButtowski: NullPointerException (我刚刚编辑了 OP 的问题并添加了 nullpointerexception 标签)
  • @user2684186:请注意,您不应在双重嵌套的 for 循环中实例化新的 ImageIcon (而且在每次绘制时都会调用该循环)。您应该事先阅读您的图块并从那里绘制。

标签: java arrays nullpointerexception tile


【解决方案1】:

x 和 y 是错误的方法

public void draw(Graphics2D g2d){
    for(int y = 0; y < mapArray.length; y++){
        for(int x = 0; x < mapArray[y].length; x++){ //you want to use y here not 0
            if(mapArray[y][x] == 1){                 //first box is outer array second is inner one
                ImageIcon ic = new ImageIcon("/Textures/stone.jpg");
                g2d.drawImage(ic.getImage(), x, y, null);
            } else if(mapArray[y][x] == 0){
                ImageIcon ic = new ImageIcon("/Textures/water.jpg");
                g2d.drawImage(ic.getImage(), x, y, null);
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    我可能会在您的代码中看到两个潜在的大问题,在您的代码中,“y”代表行,“x”代表列,但在您的 if 语句中,您选择 [column][row] 并且在试运行时您是可能计算 [row][column],其次你总是计算第一行中存在的列。如果您的数据结构在这种情况下始终为 nXn,它将起作用,但在任何其他情况下,您会得到不同的结果,并且您可能会遇到 ArrayIndexOutofBound 异常。

    【讨论】:

      猜你喜欢
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多