Consolidation of multiple inputs

when I get input from a user, I want to make sure that both of them:

  • number
  • more than the minimum value

For this, I wrote the following code, but it seems more confusing than it should be. Is there a way to consolidate the question, is the input a number and is this number less than ten or any similar two-part check?

// function prompts user for a double greater than number passed in
// continues to prompt user until they input a number greater than
// the minimum number 
public static double getInput(double minimumInput) {
   Scanner scan = new Scanner(System.in);
   double userInput;

   System.out.print("Enter a number greater than " + minimumInput + ": ");
   while (!scan.hasNextDouble()){
      String garbage = scan.next();
      System.out.println("\nInvalid input.\n");
      System.out.print("Enter a number greater than " + minimumInput + ": ");
   } // end while

   userInput = scan.nextDouble();

   while (userInput <= minimumInput) {
      System.out.println("\nInvalid input.\n");
      userInput = getInput(minimumInput);
   }

   return userInput;
} // end getInput
+4
source share
2 answers

The simple answer is no.

, . nextDouble(), . java : , .

"" . , , . , , , if.

, . , " " , " " , .

+2

|| OR ORR , :

public static double getInput(double minimumInput) {
           Scanner scan = new Scanner(System.in);
           double userInput =0;
           System.out.print("Enter a number greater than " + minimumInput + ": ");
           //Combine two vlidations using || operator
           while (!scan.hasNextDouble() ||  ((userInput=scan.nextDouble()) < minimumInput)){
              System.out.println("\nInvalid input.\n");
              System.out.print("Enter a number greater than " + minimumInput + ": ");
           } // end while
           return userInput;
        } // end getInput

, : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

0

Source: https://habr.com/ru/post/1659207/


All Articles