do{
do{
System.out.print("Enter number" + count + ":");
if(scan.hasNextInt()){
d1 = scan.nextInt();
count ++;
}
else{
System.out.print("Number is invalid. ");
scan.next();
continue;
}
t+=d1;
}while(count<=5);
total = t / 5;
System.out.print("The average is :" + total + " ." );
System.out.print(" [do you want to continue press[ y ]for yes and [ n] for no ]:");
我尝试将 t+= 放在括号内部和外部,但效果不佳,但结果仍然相同 这部分是我感到困惑的地方,因为 t+=d1 会堆积更多的循环,例如我所有的 5 个数字都是 25 那么平均值是 25 然后我按 y 然后循环回来我输入相同的 5 of 25 然后平均值是 50
推荐:
这是一个测试课:
class StackOverflowTest {
// regex pattern
private static final String REGEX_Y_OR_N = "^[yn]$";
@Test
void execute() {
Scanner scan = new Scanner(System.in);
String needToContinue = "x";
// loop until the user press "n"
do {
// for each iteration, tot and count will be reinitialized
int tot = 0;
int count = 0;
// loop until the user enter 5 numbers
do {
System.out.print("Enter a number : ");
int input;
if (scan.hasNextInt()) {
input = scan.nextInt();
count++;
} else {
System.out.println("Number is invalid."+"\n");
scan.next();
continue;
}
tot += input;
} while (count < 5);
double avg = tot / 5;
System.out.println("The average is : " + avg + " .");
System.out.println("\n"+" [do you want to continue press [ y ] for yes and [ n ] for no ]: ");
// loop until a valid character is entered ("y" or "n")
do {
needToContinue = scan.next();
if (!needToContinue.matches(REGEX_Y_OR_N)) {
System.out.println("\n"+"Invalid character!"+"\n");
System.out.println(" [do you want to continue press [ y ] for yes and [ n ] for no ]: ");
}
} while (!needToContinue.matches(REGEX_Y_OR_N));
} while (needToContinue.contains("y"));
scan.close();
}
}