[英]Java loop until user enters a value of 0. The values must be between 1-4 and if over 4, ask user to try inputting again
I need to create a loop where the user can input any amount of numbers between 1-4 and then I calculate the average.我需要创建一个循环,用户可以在其中输入 1-4 之间的任意数量的数字,然后计算平均值。 Typing 0 will end the program and calculate the average.键入 0 将结束程序并计算平均值。 Any value greater than 4 or less than 0 should not count and ask the user to input the value again.任何大于 4 或小于 0 的值都不应计数并要求用户再次输入该值。 I'm stuck on the last part.我被困在最后一部分。 I'm not sure if the while loop is the correct loop to use either.我不确定 while 循环是否是正确的循环使用。 Thanks for any help谢谢你的帮助
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
double count = 0;
while(input.hasNextInt()) {
int num = input.nextInt();
if (num == 0)
break;
if (num > 4)
System.out.println("Invalid number");
sum += num;
count += 1;
}
System.out.println("Average: " + sum/count);
}
You will always hit the lines:你总是会碰到以下几行:
sum += num;
count += 1;
Because the code just drops through from the second if statement.因为代码只是从第二个 if 语句中退出。
The following would work - note the else if and else blocks will only be executed when the first if drops through:以下是可行的 - 请注意 else if 和 else 块只会在第一个 if 掉线时执行:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
double count = 0;
while(input.hasNextInt()) {
int num = input.nextInt();
if (num == 0) {
break;
}
else if (num > 4) {
System.out.println("Invalid number");
}
else {
sum += num;
count += 1;
}
}
System.out.println("Average: " + sum/count);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.