4

当我从用户那里得到输入时,我想确保两者都是:

  • 一个号码
  • 大于最小值

我编写了以下代码来实现这一点,但它似乎比它必须的更复杂。有没有办法巩固问题是输入一个数字并且该数字是否小于十,或任何类似的两部分验证?

// 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

2 回答 2

2

简单的回答:没有。

你看,用户输入可以是任何东西。如果您不使用“nextDouble()”方法,您的代码甚至必须将字符串转换为数字。但是java中没有办法说:这个东西是一个double,必须比其他一些值小。

您必须明确地将该约束“放下”到代码中。从这个角度来看,您现在拥有的代码很好。我什至认为这比其他答案中的提议要好,后者试图将所有这些测试塞进一个 if 条件中。

你看,好的代码很容易被阅读和理解。当然,“更少的代码”通常更容易阅读,但有时“多一点”的代码可以比更短的版本更快地理解!

于 2016-10-28T17:28:27.323 回答
0

您可以使用 || 短路 OR 运算符来合并两个验证,如下所示:

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

于 2016-10-28T17:34:21.663 回答