Home > Net >  Tic Tac Toe Java Invalid user input when entering letters rather than numbers
Tic Tac Toe Java Invalid user input when entering letters rather than numbers

Time:01-02

When a user inputs a letter rather than a number an InputMistmatchException error occurs and the program exits.

How can I change it so that the program will print "Invalid input, please enter a number" instead of just exiting? Is there another way other than using catch? I found that online but I don't think my teacher will allow it.

This is my Main class if it helps

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
  TicTacToe game = new TicTacToe();
  Scanner scanner = new Scanner(System.in);
  
    game.printBoard();
    System.out.println(game.getDirections());
    
    // Keep playing the game until it is over
    while (!game.checkWin()) {
      // Read the next move from the user
      int move = scanner.nextInt();
      
      // Make the move and update the game state
      boolean spaceNotOccupied = game.checkInput(move);
            if (spaceNotOccupied) {
                game.makeMove(move);
            }
      
      // Check if the game is over
      if (game.checkWin()) {
        game.printResults();
        return;
      }
      
      // Change the current player and print the updated game board
      game.changePlayer();
      game.printBoard();
      System.out.println(game.getDirections());
    }
    
    // Print the final result of the game
    game.printResults();
    
    }
  }


  

And this is the makeMove method where it shows the numbers to enter

  
  public void makeMove(int space) {
  // Update the game board
    if (space == 1) {
    s1 = turn;
  } else if (space == 2) {
    s2 = turn;
  } else if (space == 3) {
    s3 = turn;
  } else if (space == 4) {
    s4 = turn;
  } else if (space == 5) {
    s5 = turn;
  } else if (space == 6) {
    s6 = turn;
  } else if (space == 7) {
    s7 = turn;
  } else if (space == 8) {
    s8 = turn;
  } else if (space == 9) {
    s9 = turn;
  } else {
      System.out.println("Invalid input, please try again.");
      return;
    }
  }

CodePudding user response:

Instead of directly assuming (using) the input as Integer, first verify if it is Integer of not. If not, loop till you get one.

// Read the next move from the user    
System.out.print("Please provide your next move");
while (!scan.hasNextInt()) {
     System.out.print("Invalid input, please enter a number");
     scan.next();
}
     
int move = scan.nextInt();

CodePudding user response:

You can use infinite loop to do that, but you need to check if the user is winning for every valid input.

boolean playing = true;
while(playing){
   switch(space){
      case 1:
           //code for doing operation
           //winning check
           break;
      ...
      default:
           System.out.println("Invalid Input");
   }          
}
  • Related