如何循环但使值返回0?变量d1是对输入进行叠加,使平均值翻倍


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将叠加更多的I循环,例如,我所有的5个数字都是25,然后平均值是25,我按y,然后循环回来,我输入相同的25中的5,然后平均数是50

欢迎使用StackOverflow。

建议:

  • 如果您想要更快的答案,请共享可运行的代码
  • 始终缩进代码,这样会更容易阅读
  • 变量的名称非常重要,所以请给它们一个合适的名称,以了解它们包含的内容。(例如,您声明了一个变量"total",它将包含平均结果,将其称为"avg"或"average"是合理的。(

这是一个测试类:

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();
}

}

最新更新