当我从用户那里得到输入时,我想确保两者都是:
- 一个号码
- 大于最小值
我编写了以下代码来实现这一点,但它似乎比它必须的更复杂。有没有办法巩固问题是输入一个数字并且该数字是否小于十,或任何类似的两部分验证?
// 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