0

I am trying to code this program that asks the user for the value of x1, and to create an exception if the user inputs something other than an integer. However, when I use the InputMismatchException, I keep getting an error saying that it can not be converted to a throwable?

Here is my code :

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    int x1 = getScannerInt("Enter x1");

}

public static int getScannerInt(String promptStr) {
    Scanner reader = new Scanner(System.in);
    int x1 = 1;
    boolean continueLoop = true;
    while (continueLoop) {
        System.out.println("Enter x1: ");
    }
    {
        try {
            x1 = reader.nextInt();
            continueLoop = false;
        } catch (InputMismatchException e) {
            System.out.println("Please only enter numbers");

        }
    }
    return x1;

}

I will appreciate any help!

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Celina
  • 3
  • 3
  • Maybe you didn't import the `java.util.InputMismatchException`? Else it should compile, but never do what you want. The `while (continueLoop) System.out.println("Enter x1: ")` is an infinite loop, you are not consuming the newline char (see YCF_L's answer). – Seelenvirtuose Oct 28 '17 at 09:11
  • On an unrelated note, you seem to have an infinite loop going on there. You put the print statement before the opening brace in the loop. (Edit, just saw @Seelenvirtuose said the same thing) – Matt Oct 28 '17 at 09:13

1 Answers1

0

You have to consume the new line using reader.nextLine(); like this :

while (continueLoop) {
    System.out.println("Enter x1: ");
    try {
        x1 = reader.nextInt();//this does not consume the last newline
        continueLoop = false;
    } catch (InputMismatchException e) {
        System.out.println("Please only enter numbers");
    }
    reader.nextLine();//You can consume it using nextLine()
}

Note :

When you use

while (continueLoop) 
     System.out.println("Enter x1: ");

the only instruction that work after the while is System.out.println("Enter x1: ");, be careful.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 1
    Hmmm ... How does handling the newline char answer the question "I keep getting an error saying that it can not be converted to a throwable?" Besides that, the code has some other problems, too. An infinite loop, for example. – Seelenvirtuose Oct 28 '17 at 09:14
  • @Seelenvirtuose it work fine with me when i use this piece of code, yes i agree there are another problem with this code, which is the brackets `{}` – Youcef LAIDANI Oct 28 '17 at 09:18