0

When using scanner is there a way to check that the user input is what we expect?

Say I want a double but the user enters a String what can I do to prompt the user to re-enter the value as a double?

With the following code if a number is not entered I get a mismatchException. I don't want the program to crash if the input is wrong.

Here is my code: import java.util.Scanner;

public class RoundingNumbers {

  private double y;
  private double x;
  public RoundingNumbers(){
    double y = 0;
    double x = 0;
  }

  public void getNumber(){
    System.out.print("Enter a decimal number: ");
    Scanner num = new Scanner(System.in);
    x = num.nextDouble();
  }

  public void roundNum(){
    y = Math.floor(x + 0.5);
  }

  public void displayNums(){
    System.out.println("The actual number is: " + x);
    System.out.println("The rounded number is: " + y);
  }

}
Krayo
  • 2,415
  • 4
  • 23
  • 43
Mac
  • 185
  • 5
  • 9
  • 17
  • possible duplicate of [Validating input using java.util.Scanner](http://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner) – BackSlash Oct 14 '14 at 19:43
  • Trap the MismatchException within a while loop. If the value is valid, set the exit value for the loop to "true", in the exception catch block, set it to "false"... – MadProgrammer Oct 14 '14 at 19:48
  • @MadProgrammer Since the `Scanner` class provides methods to check without having to catch exceptions, I would prefer doing that way – BackSlash Oct 14 '14 at 19:49
  • @BackSlash since either you handle the scanner exception or the parser exception, you're still handling exceptions... – MadProgrammer Oct 14 '14 at 20:11
  • @MadProgrammer I'm not talking about exceptions. The `Scanner` class provides the `hasNextDouble()` method, which can be used instead of using `try-catch`. You can just use `if(scanner.hasNextDouble()) myDouble = scanner.nextDouble()`. No `try-catch` here – BackSlash Oct 15 '14 at 08:16

2 Answers2

1

You can wrap it in a try catch block. See the below example function.

Whoops. I wasn't paying close enough attention and didn't see your code example.

Change your getNumber() function to the below definition. Note that there are many different ways to do this. This is just an example.

public void getNumber(){
    Scanner num = new Scanner(System.in);
    while(true) {
        System.out.print("Enter a decimal number: ");
        try {
           x = num.nextDouble();
           break;
       catch(InputMismatchException e) {}
    }
}
abalos
  • 1,161
  • 6
  • 12
0

You already noticed that you recieve a InputMismatchException if they don't type what you expect. With this in mind, you can surround the x = num.nextDouble() with a try-catch block and check for that kind of Exception. For example:

while (true) {
    try {
        x = num.nextDouble();
        // move along if no exception is thrown
        break;
    } catch (InputMismatchException e) {
        // give the user an error message
        System.out.println("Type mismatch when reading your input. Please insert a double: ");
    }
}

By the way, this is not directly related to your question, but you shouldn't name your Scanner variable as num, because that name doesn't make anyone think of a Scanner - people in general would think it's an int or something. It's a good programming practice to give your variables names that fits them.

Pedro A
  • 2,582
  • 2
  • 19
  • 46
  • The above code creates an infinite loop. Am I missing something? – Mac Oct 15 '14 at 18:52
  • If the call to `num.nextDouble()` do not throw an exception, the program will reach the `break` and therefore end the loop. Unless the user keeps inserting non-doubles for ever, the loop won't be infinite. – Pedro A Oct 15 '14 at 19:07
  • I know its not an infinite loop if a double is entered but if I just enter a letter once the error message is repeated infinitely. It doesn't allow for another user input. – Mac Oct 15 '14 at 23:29