简体   繁体   中英

For loop to change background color

Hi I'm creating a Battleship program for my Java class. Right now, I'm trying to work on a class that fires shots. To fire, I'm trying to change the background color from blue(which means it is just an empty cell) to yellow (to show that I have fired in that cell but there is nothing there).

This is the code for the Fire class. I can include the other classes it inherits from if you think it's necessary. The main thing I'm having a problem with is trying to get my "for" loop to go through and really change the background from blue to yellow for the number of iterations I want it to. 100 is an arbitrary number for testing purposes.

public class Fire extends Ship{

    public Fire() throws InterruptedException{
        super.setShipV();
    }
    public void Shoot() throws InterruptedException {

        Random random= new Random();

        int a = random.nextInt(100);
        int b = random.nextInt(100);

        for (int i = 0; i< 100; i++){
           //for(int j = 0; j< 50; i++){
           grid[a][b].setBackground(Color.yellow);
        }
    }
}

Thanks for your help.

Hannah

You need to use the iterator variables when accessing the grid.

Try something like this:

for (int i = 0; i< 100; i++){
   for(int j = 0; j< 50; i++){
      grid[i][j].setBackground(Color.yellow);
}

or if you want to change 100 random fields put the random.nextInt inside the loops so a and b change in each iteration (The random values can hit the same values as previous iterations)

for (int i = 0; i< 100; i++){
   int a = random.nextInt(100);
   int b = random.nextInt(100);
   grid[a][b].setBackground(Color.yellow);
}

The only code that gets executed in each iteration is the code between { (after for(..) ) and } . This means that in your code a and b are set once and then you are marking the same grid field yellow a hundred times. If you do it this way you give a and b a new value in each iteration.

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