当我从用户那里得到一个输入时,我想确保它们都是:
>数字>大于最小值
我编写了以下代码来实现这一目标,但它似乎比它必须更复杂.有没有办法合并问题的是输入一个数字,这个数字是否小于十,或任何类似的两部分验证?
// 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
最佳答案 简单的回答:没有.
你看,用户输入可以是任何东西.如果您不使用“nextDouble()”方法,您的代码甚至必须将字符串转换为数字.但是在java中没有办法说:这个东西是双重的,它必须小于其他一些值.
您明确必须将该约束“放下”到代码中.从这个角度来看,你现在拥有的代码很好.我甚至认为它比其他答案中的提议更好,它试图将所有这些测试填充到单个if条件中.
你看,好的代码可以很容易地阅读和理解.当然,“更少的代码”通常更快阅读,但有时“更多”的代码可以比更短的版本更快地理解!