Search code examples
javafor-looplogicminesweeper

Issues with logic in a nested for loop


Closely related to Java programming - nested for loops for minesweeper game, my Minesweeper program is designed to loop through cells, check each adjacent cell, perform a logic test to check if it's a Mine, and then jump to the next one. However, when I run it, it somehow becomes an infinite loop. I've tried changing variables, reversing signs (< becomes > and + becomes -), and googling other solutions, but I can't find anything.

Printouts are for debugging, gameboard is set to [10][10],

public static void assignNumbers(int[][] gameBoard)
   {

      for(int r = 0; r <= (gameBoard.length - 1); r++){ //row
         for(int c = 0; c <= (gameBoard[0].length - 1); r++){ //column

            System.out.print("New Cell   ");

            for(int vR = r+1; vR > r-2; vR --){ //vR is visiting Row
               for(int vC = c+1; vC > c-2; vC --){ //vC is visiting Column

                  System.out.print("new item  ");
                  if (isValid(vR, vC, gameBoard)){

                     System.out.print("isMine?  "); 
                     if (isMine(vR, vC, gameBoard)){ 
                        gameBoard[r][c] += 1;
                        System.out.print("   MINE   "); 
                     } 
                     else {
                        System.out.print("   NO     ");
                     }
                  }               
               }
            }  
            System.out.println();          
         }         
      }
   }

public static boolean isMine(int r, int c, int[][] gameBoard){
      if(gameBoard[r][c] != 100){
         return false;
      }
      else{
         return true;
      }
}

public static boolean isValid(int r, int c, int[][] gameBoard) 
   { 
       // Returns true if row number and column number 
       // is in range 
      return ((r >= 0) && (r < SIDE)) && ((c >= 0) && (c < SIDE)) && !isMine(r, c, gameBoard); 
   } 

When I try to run it, I get an infinite printout saying : "New Cell" followed by 9 "new items". This should only print out 100 times (once for each cell), however it doesn't stop after 100. I assume it's a logic error in one of the for loops, but I can't find it for the life of me. Any help is appreciated, and I'll do my best to answer any questions.

EDIT: punctuation


Solution

  • Try to replace r++ with c++

    for(int c = 0; c <= (gameBoard[0].length - 1); c++){ //column