System.out.println("Enter the first test score:");
double test1 = input.nextInt();
if (!(test1 >= 0 && test1 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
System.out.println("Enter the second test score:");
double test2 = input.nextInt();
if (!(test2 >= 0 && test2 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
如果我提示用户输入test1的值及其在特定范围内的值,我该如何再次提示他输入正确的值?现在,如果我运行并输入一个错误的值“这超出了可接受的范围,请输入一个介于0到100之间的数字”msg会显示但它会直接进入test2。我试着这样做
System.out.println("Enter the first test score:");
double test1 = input.nextInt();
if (!(test1 >= 0 && test1 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
double test1 = input.nextInt();
但我收到错误信息。 我是否必须使用循环,如果是这样的话?
答案 0 :(得分:1)
那是因为你宣布test1
两次。
double test1 = input.nextInt();
if (!(test1 >= 0 && test1 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
--> double test1 = input.nextInt(); //Look at this line
试试以下内容: double test1 = input.nextInt();
if (!(test1 >= 0 && test1 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
test1 = input.nextInt();
对于更干净的代码,请使用以下方法:
public double getValue(){
double test1=input.nextInt();
if (!(test1 >= 0 && test1 <= 100)){
return getValue();
}else{
return test1;
}
}
除非根据!(test1 >= 0 && test1 <= 100)
条件输入正确,否则以上代码将继续接受用户输入。
答案 1 :(得分:0)
首先,你宣布test1两次,第二次 - 你可以使用循环
double test1 = input.nextInt();
while(!(test1 >= 0 && test1 <= 100))
{
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
/*double */test1 = input.nextInt();
}
答案 2 :(得分:0)
尝试类似
的内容double test1 = input.nextInt();
while(!(test1 >= 0 && test1 <= 100)) {
System.out.println("Enter a valid number");
test1.nextInt();
}
我们的想法是提示用户 ,直到 输入有效输入。如果你使用简单的if语句或一个固定的for-loop,你最终只会要求一个固定数量的正确值。
您应该记住的另一件事是:
if (!(test1 >= 0 && test1 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
double test1 = input.nextInt(); //There is no need to declare test1 again. Remove double
将编译为
if (!(test1 >= 0 && test1 <= 100))
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
test1 = input.nextInt(); //This is not part of the if!!!!
所以你必须使用像
这样的括号if (!(test1 >= 0 && test1 <= 100)) {
System.out.println("This is out of the acceptable range, please enter a number between 0 and 100 .");
test1 = input.nextInt();
}