0

I'm writing a simple game that asks a user to type in an integer. If they type in anything else I want to tell them it was invalid and have them try again. I am using eclipse and it seems like no matter what I try when the user(me) puts in an invalid entry my program stops.

I have even tried to use the "finally" method after the catch because everyone says the code will run but it does not. I have tried to use a loop but that is not working either. any ideas or reasons? keep in mind I am brand new to Java and I'm on my second project in the microsoft course so there is a lot i do not understand.

I am assuming I need to write the solution in the catch area but I dont know.

import java.util.InputMismatchException;
import java.util.Scanner;

public class Play {

public Play() {

    Scanner input = new Scanner(System.in);

    try {
        System.out.println("Choose how many fingers you wish to play.");
        input.nextInt();

        if(input.nextInt() < 0 || input.nextInt() > 10) {
            System.out.println("That is not a valid number. Please enter a number between 1 and 10.");
            input.nextInt();
        }else if(input.nextInt() > 0 && input.nextInt() < 11) {
            System.out.println("Great, you chose "+input.nextInt()+" fingers.");
        }
    }catch(InputMismatchException notInt) {
        System.out.println("That was not a number!");
    }
}

}

Swaraj
  • 345
  • 3
  • 17

1 Answers1

0
  • You're not assigning input.nextInt() to a variable.
import java.util.InputMismatchException;
import java.util.Scanner;

class Play {
    public Play() {
        Scanner input = new Scanner(System.in);
        try {
            System.out.println("Choose how many fingers you wish to play.");
            int n = input.nextInt();
            if (n > 0 && n < 11) System.out.println("Great, you chose " + n + " fingers.");
            else System.out.println("That is not a valid number. Please enter a number between 1 and 10.");
        } catch (InputMismatchException notInt) {
            System.out.println("That was not a number!");
        }
    }
}
Ankit Sharma
  • 1,626
  • 1
  • 14
  • 21