我为课堂活动编写的以下程序旨在提示用户在0到100之间的无限数量的测试标记,并且当用户输入超出该范围的标记时,它应该告诉用户其无效标记(到目前为止在我的程序中有效)。当用户输入“ -1”时,它应停止程序,然后打印出这些标记的平均值。
import java.util.*;
public class HmWk62 {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int count=1;
int mark, total=0;
double average;
System.out.println("please enter mark "+count);
mark = console.nextInt();
count++;
while ((mark >= 0)&&(mark <= 100)){
System.out.println("Please enter mark "+count);
mark = console.nextInt();
total += mark ;
++count;
while ((mark < 0)||(mark > 100)){
System.out.println("Invalid mark, please re-enter");
mark = console.nextInt();
}
}
}
}
当用户输入“ -1”时,它应停止程序,然后打印出这些标记的平均值。
好吧,如果用户输入-1,您将永远不会退出验证输入的嵌套循环。
如果要允许-1,则应在嵌套循环中更改条件以允许它:
while (mark < -1 || mark > 100)
还要注意,在验证之前,您正在使用的值mark
-因此,如果输入10000,在输入total
新值之前,您仍会添加10000-然后您将忽略新值。
另外,mark
除了查看是否应进入循环外,根本不使用输入的第一个值。
我怀疑您实际上想要的是:
while (true) {
int mark = readMark(scanner, count);
if (mark == -1) {
break;
}
count++;
total += mark;
}
// Now print out the average, etc
...
private static int readMark(Scanner scanner, int count) {
System.out.println("Please enter mark " + count);
while (true) {
int mark = scanner.nextInt();
if (mark >= -1 && mark <= 100) {
return mark;
}
System.out.println("Invalid mark, please re-enter");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句