如何循环但使值回到 0 变量 d1 正在堆叠输入,使平均值翻倍?

问题描述 投票:0回答:1
   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

java nested do-while
1个回答
0
投票

推荐:

  • 如果您想要更快的答案,请分享可运行的代码。
  • 始终缩进你的代码,这样会更容易阅读。
  • 变量的名称非常重要,所以请给它们一个合适的名称以了解它们包含的内容。 (例如,您声明了一个变量“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();
    }
    
}
© www.soinside.com 2019 - 2024. All rights reserved.