0

I know there are lots of questions similar to this but I can't understand most of it, also I can't see any similar questions related to java language. So can you guys help me how to loop this question if the input is not a double data type? The code:

          System.out.println("Enter first number");
          num1 = input.nextDouble();
         
          System.out.println("Enter second number");
          num2 = input.nextDouble();   

I really appreciate anyone who tries to answer, tia!!

2 Answers2

0

This is a solution (without exception handling). It loops until two Doubles have been entered. So it is possible to enter this:

3
4.2

or also:

www
3
abc
4.2

Both will give the same result

3
4.2

Note that the code is locale sensitive in regard of the numbers you enter at the command prompt (meaning that the decimal sign depends on your computer settings – in Germany for example it is the comma and not the dot, so you would enter 4,2):

Scanner scanner = new Scanner(System.in);

Double part1 = null;
Double part2 = null;

while (true) {
  if (scanner.hasNextDouble()) {
    if (part1 == null ) {
      part1 = scanner.nextDouble();
    } else {
      part2 = scanner.nextDouble();
      break;
    }
  } else {
    scanner.next();   // The input is not a Double, so just drop it
  }
}

scanner.close();

System.out.println(part1);
System.out.println(part2);

If you add the line scanner.useLocale(Locale.ROOT) after creating the scanner:

Scanner scanner = new Scanner(System.in);
scanner.useLocale(Locale.ROOT);

the decimal sign will be the dot '.' like in 4.2 independent of the settings of your computer.

lukas.j
  • 6,453
  • 2
  • 5
  • 24
0

I like to create a separate method to validate input. If the value is invalid, then I have the method return -1. Then I'll have a while loop that checks if the input is -1, if so, than it'll ask the for a new input value till it's correct. There are many ways to go about it. But the gist is something like this.

public static void main(String[] Args) {

    Scanner input = new Scanner(System.in);

    System.out.println("Enter first number");
    double num1 = validateDouble(input);

    while (num1 == -1) {
        num1 = validateDouble(input);
    }

    System.out.println(num1);
}


    private static double validateDouble(Scanner scanner) {
        String input = scanner.nextLine();
        try {
            double i = Double.parseDouble(input);;
            return i;
        }catch (InputMismatchException | NumberFormatException e) {
            if (input.equals("q")) {
                System.exit(0);
            }
            System.out.println("Please try again.");
            return -1;
        }
    }
JonR85
  • 700
  • 4
  • 12