RJB RJB - 7 months ago 20
Java Question

Error scanning invalid input

This program needs to return 'Invalid Input' if anything other than a row between 0-4 is input, currently I am getting the error:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at ass.Puzzle.play(Puzzle.java:147)
at ass.Puzzle.main(Puzzle.java:18)

Answer

You need to catch the thrown exception

else if (input.equals("c")) {
    System.out.println("What column? (1-4)");

    try{
        int column = s.nextInt();
        s.nextLine();
        if (column <= 4){
            rotateColumn(currentarr,column - 1);
            print(currentarr);
            b++;
        }
        else
           System.out.println("Invalid Input");
     }catch (InputMismatchException ex){
         System.out.println("Invalid Input");
     }