-1

If the user enter a non-numeric value for example "Hello", I want to give the user a new chance to enter a numeric value until he succeeds.

Running the code below, the text "This is not a numeric value. Enter a numeric value: ", will show in the console, if the user enters a non-numeric value. However, the user will not be able to enter a new value. Because the error message "Exception in thread..." will show and stop the program.

How do I solve this?

Edit!
New code (This code works, except it stops the program completely. Every method called afterwards, won't run.) Edit2! It did not work!

int number;

do {
  try {
    System.out.println("Enter a numeric value: ");
    number = Integer.parseInt(s.nextLine());

    if (s.nextInt() != (int)number) {
      throw new NumberFormatException();
    }
    break;
  }
  catch (NumberFormatException e) {
    System.out.println("This is not a numeric value. Enter a numeric value: ");
  }
} while (true)

Old code

int number;

try {
  Scanner s = new Scanner(System.in);

  System.out.println("Enter a numeric value: ");
  number = s.nextInt();

  if (number != (int)number) {
    throw new Exception();
  }
}
catch(Exception e) {
  do {
    System.out.println("This is not a numeric value. Enter a numeric value: ");
    number = s.nextInt();
  } while (number != (int)number);
}
  • 2
    You have a do-while loop inside your catch block. Where else could you move that loop to in order to continuously prompt the user for input while simultaneously catching non-numeric inputs? – Jacob G. Jul 15 '20 at 17:32
  • 2
    The check `number != (int)number` is meaningless, since `number` is an `int`. You won't get to that line if your input is not an `int. – RealSkeptic Jul 15 '20 at 17:42
  • Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – alea Jul 15 '20 at 18:09

5 Answers5

2

Use NumberFormatException instead of Base Exception Class

int number;
Scanner s = new Scanner(System.in);
System.out.println("Enter a numeric value: ");

do {
    try {

        number = Integer.parseInt(s.nextLine());
        //Do your work
        break;
    } catch (NumberFormatException e) {
        System.out.println("This is not a numeric value. Enter a numeric value: ");

    }
}
while (true);

}
  • This did solve the problem I displayed. However, it completely stops the program. Any methods called afterwards don't run. Do you have a way to fix that? –  Jul 15 '20 at 18:32
1

Please try below given code:

int number;
Scanner s = new Scanner (System.in);
  System.out.println ("Enter a numeric value: ");

do
  {
try
{

  number = Integer.parseInt (s.nextLine ());
  //Do your work
  break;
}
catch (Exception e)
{
  System.out.println
    ("This is not a numeric value. Enter a numeric value: ");

}
  }
while (true);

}
Ashish Karn
  • 1,074
  • 1
  • 9
  • 20
1

It sounds like you want to loop forever until the user enters a valid integer. A common way to express "loop forever" is with while (true) {...}. This is an "infinite loop." The only way to exit this loop is with a break statement or a return statement (or by throwing an exception, but in this case you want to catch the exception and continue looping).

One problem with using scanner.nextInt() is that if the value is not an integer, the value will remain in the scanner's buffer. If you keep calling nextInt(), you'll just keep getting InputMismatchExceptions since the scanner will keep trying to interpret the same bad input as an integer, over and over again.

One way around that problem is to use scanner.nextLine() to read the value as a String, and then use Integer.parseInt(String) to convert the String to an int. If the conversion fails, Integer.parseInt(String) throws a NumberFormatException. You can handle this exception by catching it.

Here's a little function that loops forever until the user enters a value that can be parsed as an int:

public static int promptForInt(Scanner scanner) {
  while (true) {
    System.out.println("Enter a numeric value:");
    try {
      return Integer.parseInt(scanner.nextLine());
    } catch (NumberFormatException e) {
      System.out.print("This is not a numeric value. ");    
    }
  }
}

You can call the method like this:

Scanner scanner = new Scanner(System.in);
int number = promptForInt(scanner);
dnault
  • 6,664
  • 1
  • 27
  • 44
1

I don't think you truly understand where the exception is coming from. The line throw new Exception(); never runs in your code. This is because your if statement says if (number != (int) number), which will never be true because the variable number is already of the type int, so you are basically saying if (number != number), which can never be true. If you take a look at Scanner's nextInt() method, you'll notice that it actually throws InputMismatchException. That is the exception you are catching with your try-catch, but it is not the exception that is causing the error message. So where is that exception coming from? The line number = s.nextInt(); is not compilable code. You defined s inside the try block, so therefore s only exists inside the try block. You get an exception when you try to access it in the catch block because s is not a variable there; it does not exist as far as the compiler is concerned. The fix is pretty simple; just move the declaration for s to outside the try block, and put the while loop around the try-catch block. Also remember to consume the line separators in the input stream using s.nextLine() every time you try to read an int. Here's an example of how I would do it:

int number;
Scanner s = new Scanner(System.in); //declare s outside of the try block

System.out.println("Enter a numeric value: ");

while (true) { //while loop goes around the try-catch block
  try {
    number = s.nextInt(); //this could throw InputMismatchException
    break; //if no exception is thrown, break out of the loop
  } catch (InputMismatchException e) { //if the exception is thrown
    s.nextLine(); //consume the line separator character(s)
    System.out.println("This is not a numeric value. Enter a numeric value: "); //prompt the user for another value
    //this will then go back to the top of the try block again, because we never broke out of the while loop
  }
}

s.nextLine(); //consume the line separator character(s)
Charlie Armstrong
  • 1,955
  • 2
  • 7
  • 16
0

Try the following, if you take your input as a string you can parseInt to check if its an integer value

    String number = null;

    Scanner s = new Scanner(System.in);

    System.out.println("Enter a numeric value: ");
    number = s.next();

    try {
        // checking valid integer using parseInt() method
        Integer.parseInt(number);

    } catch (NumberFormatException e) {
        System.out.println("This is not a numeric value. Enter a numeric value:");
        number = s.next();

        // put this line here to prove it accepted the second attempt
        System.out.println("Your entered integer is:" + number);
    }
    s.close();

}

}

Kyle Moffett
  • 126
  • 1
  • 9