I am in an intro to java class and have we have to create a Mine Sweeper game. I have the game complete for the most part. But I have having 1 issue where my program goes into a crazy infinite loop.
When the user Guesses wrong and hits a "bomb", the game correctly ends. But when they guess correctly and do not hit a bomb, the program enters a infinite loop for some reason and I have to terminate it.
I use 2 2dArrays, one that displays to the player as all '?', and the other that has actual bombs placed on it, that I compare guesses to and update the player board. I feel like the problem is in my GetGuess method. Not sure why this infinite loop only happens the the user makes a correct guess.
The first guess prompt works fine, and if it hits a bomb, the game ends. If the guess is good, the program should ask for another guess, but instead The infinte loop prints:
Enter row number:
null
over and over again until I terminate. Can anyone help me figure out where this is coming from?
Here is my main and Game class.
public class MineSweeper {
public static void main(String[] args) {
Game test = new Game();
test.loadBombs(test.bombBoard);
test.loadArray(test.board);
test.loadNumber(test.bombBoard);
test.displayBoard(test.board);
test.displayBoard(test.bombBoard);
while(test.gameOver==false)//Continue to get user guess until win or lose
{
test.getGuess(test.board, test.bombBoard);
test.displayBoard(test.board);
}
}
public class Game {
int arrayDimension = 9;
char[][] board = new char[arrayDimension][arrayDimension];
char[][] bombBoard = new char[arrayDimension][arrayDimension];
static boolean gameOver;
public static void getGuess(char[][] boardArray,char[][]bombBoard)
{
int rowGuess = 0, colGuess=0;
Scanner reader = new Scanner(System.in);
//Prompt user guess
boolean valid = false;//Check if guess is valid
while(valid == false)
{
try{
System.out.println("Enter row number: ");
rowGuess= reader.nextInt();
System.out.println("Enter column number: ");
colGuess = reader.nextInt();
if((rowGuess<0||rowGuess>8) && (colGuess<0||colGuess>8))//Check if guess is valid
{
throw new IndexOutOfBoundsException("This row and column is out of bounds!");
}
else if(rowGuess<0 || rowGuess >8)
{
throw new InputMismatchException("Invalid Row Choice!");
}
else if(colGuess<0 || colGuess >8)
{
throw new InputMismatchException("Invalid Column Choice!");
}
else{}
}
catch(Exception e)
{ System.out.println(e.getMessage());
}
if(rowGuess >= 0 && rowGuess<=8) //Guess was valid, place * at location
{
if(colGuess >=0 && colGuess<=8)
{
boardArray[rowGuess][colGuess]= '*';
reader.close();
valid = true;
}
}
}
char answer = bombBoard[rowGuess][colGuess];//check bomb board with user guess
if(answer == '#')//Bomb, you lose
{
boardArray[rowGuess][colGuess]= answer;
System.out.println("You hit a bomb, game over!");
gameOver = true;
}
else//correct guess, Place number of bombs around guess, continue guessing.
{
boardArray[rowGuess][colGuess]= answer;
gameOver = false;
}
}