public int inputNumber() {
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of cookies you'd like to make ");
int number = input.nextInt();
if (number <=0) {
System.out.println(" please enter a valid number")
int number = input.nextInt();
}
input.close();
return number;
}
编辑:
我应该使用while循环..回到字面上我的第一个项目。
答案 0 :(得分:5)
System.out.print("Enter the number of cookies you'd like to make:");
int number = input.nextInt();
while(number<=0) //As long as number is zero or less, repeat prompting
{
System.out.println("Please enter a valid number:");
number = input.nextInt();
}
这是关于数据验证的。可以使用do-while
循环或while
循环来完成。您可以阅读有关使用循环的主题。
对您的代码备注:
您不应该两次声明number
。这是在您的上述代码中进行的int
number
不止一次(在同一范围内)。
答案 1 :(得分:2)
通过这种方式,您可以减少多余的打印报表,并且不需要多次声明变量。
public int inputNumber() {
Scanner input = new Scanner (System.in);
int number = 0;
do {
System.out.print("Enter the number of cookies you'd like to make ");
number = input.nextInt();
} while(number <= 0);
input.close();
return number;
}
答案 2 :(得分:0)
几个问题:
您正在使用的是否用于检查号码而不是使用,直到并且除非用户输入正确的号码,否则您不会继续。
public int inputNumber() {
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of cookies you'd like to make ");
int number = input.nextInt();
while (number <=0) {
System.out.println(" please enter a valid number");
number = input.nextInt();
}
input.close();
return number;
}
答案 3 :(得分:0)
这样做的经典方法是限制重试和中止的次数超过::
static final int MAX_RETRY = 5; // what you want
...
int max_retry = MAX_RETRY;
int number;
while (--max_retry >= 0) {
System.out.print("Enter the number of cookies you'd like to make ");
number = input.nextInt();
if (number > 0) {
break;
}
System.out.println("Please enter a valid number")
}
if (max_retry == 0) {
// abort
throw new Exception("Invalid input");
}
// proceed with number ...