0

I have a 640x640 grid that maps to an 8x8 2D array. I need to be able to draw an oval in the place that the user clicks and I'm trying to figure out a loop to do it instead of typing multiple if statements.

For example I can write this for each square on the board and it will draw the desired shape with no issue.

oldx = event.getX(); 
oldy = event.getY(); 
if(oldx<=80&&oldy<=80){
board[0][0]=1; 
    repaint(); 

}

I'm trying to make a loop and this is what I have so far, it is not working out well though. It prints in undesired locations. I think the way I have it here is that it only prints in locations that are divisible by 80. I need to take in the x and y coordinates to the 2D array.

    int x1 = oldx/80;
    int y1 = oldy/80;
    for(int r=0; r<8; r++){
      for(int c=0; c<8; c++){
          board[x1][y1] = 1;
           repaint();
         }  
       }
    }

Any help is appreciated.

4

2 回答 2

2

你似乎走在正确的道路上。但是,循环示例中没有您的条件。您需要if()在双循环中添加一条语句,for以检查选定的 X 和 Y 是否与您正在循环的当前方块相匹配。

于 2013-11-14T17:46:11.780 回答
2

这会让它为你工作。

    boolean found = false;
    while(found!=true){
    for(int r=0; r<8; r++){
        for(int c=0; c<8; c++){
        if(y1==c&&x1==r){
            board[r][c] = 1;
            found = true;
            repaint();
                }
            }
        }
    }
}
于 2013-11-14T18:38:31.133 回答