我尝试将一些值设置为整数数组,但值不会粘

时间:2013-07-04 15:35:49

标签: java arrays multidimensional-array

这是我的代码:

int[][] coordX = new int[10000][10000];
int[][] coordY = new int[10000][10000];
int cX = 0;
int cY = 0;

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int) (screenSize.getWidth());
int height = (int) (screenSize.getHeight());
BufferedImage dirt = null;
{
    try {
        dirt = ImageIO.read(new File("res/dirt.png"));
    } catch (IOException e) {
    }
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.RED);
    for (int y = 0; y <= height; y = y + 50) {
        for (int x = 0; x <= width; x = x + 50) {
            g.drawImage(dirt, x, y, 50, 50, Color.BLACK, this);
            coordX[cX][cY] = cX;
                coordY[cX][cY] = cY; 
            cX = cX + 1;
            System.out.println("X=" + coordX[cX][cY]);
        }
        cY = cY + 1;
        cX = 0;
        System.out.println("Y=" + coordY[cX][cY]);
    }
}

控制台将所有“X =”值输出为零,对于“Y =”输出相同,但是,当我自己打印“cX”和“cY”值时,它们按预期计数。当我尝试将“cX”和“cY”值存储在数组中时,似乎只会出现这个问题。

2 个答案:

答案 0 :(得分:0)

您在打印前递增cXcY。试试这个:

coordX[cX][cY] = cX;
coordY[cX][cY] = cY; 
System.out.println("X=" + coordX[cX][cY]);
System.out.println("Y=" + coordY[cX][cY]);
cX = cX + 1;

答案 1 :(得分:0)

您正在将之前的cX 递增到打印

   cX = cX + 1;
   System.out.println("X=" + coordX[cX][cY]);

即。你没有打印刚刚填充的元素。您将始终获得默认(未初始化)的int元素值(0)。