0

I need to check the user input and ask for a correct one if the value is not a digit. However when I do this code, the program displays an error message and then crashes- it does not ask the user to give a new input. How can that be fixed? Thank you!

import java.util.Scanner;
import java.lang.Math;
public class CentimeterInch
{
    public static void main (String [] args)
    {
        final int MAX=100, feet=12, meter=100;
        final double inch=2.54;
        Scanner scan = new Scanner (System.in);
        System.out.println ("This program converts distances. ");
        System.out.println ("Enter distance and unit (e.g. 37 1 or 100 2):");
        double distance=scan.nextDouble();
        if (!scan.hasNextDouble())
            {
                System.out.println ("please enter a numeric value");
                distance=scan.nextDouble();
            }
        int unitType = scan.nextInt();
        if (distance<0)
            {
                System.out.println ("Please enter a non negative distance");
            }
....
tamir
  • 155
  • 1
  • 1
  • 10
  • Helpful (duplicate?)http://stackoverflow.com/questions/2912817/how-to-use-scanner-to-accept-only-valid-int-as-input –  Oct 31 '15 at 15:28

1 Answers1

1

Just bring the if clause before performing scan.nextDouble().

 if (!scan.hasNextDouble())
 {
   System.out.println ("please enter a numeric value");
   scan.nextLine();
   distance=scan.nextDouble();
 }

double distance=scan.nextDouble();

First make sure that the number to be read is a double value, then read it. You were doing the reverse

What is scan.nextLine() doing here?

Suppose the user enters abc 2. scan.hasNextDouble() checks wether the token to be read next is a double value or not. It's not, so scan.hasNextDouble() evaluates to false and the if clause gets executed. Inside the if clause, you have scan.nextLine(). It simply discards the current input from scan, thus flushing scan. If you don't do so, then scan still contains abc 2 and upon executing distance = scan.nextDouble(), the compiler issues an error.

It's better if you replace if with while. Suppose user gives wrong input. Your program checks the input and finds out that it's not a double value. The if clause if executed and the user is asked to enter a numeric value. What if the user again enters a wrong input. This time, you will get an error. Using a while loop makes your program to keep asking the user for a correct input until he enters a numeric value.

Wololo
  • 841
  • 8
  • 20
  • Hi, thanks for you answer. I can't use while due to university restrictions at this stage, so IF is ok. Regarding the input check, I still don't get it. I'm still getting an error when I do it the way you wrote, and as far as I understand it, the bad input is still being placed into distance. I'm looking for something like Isdigit in c++ that you can put on the input before its placed into the variable – tamir Oct 31 '15 at 17:10