java 你如何循环,但使值回到0,变量d1是堆叠的输入,使平均值加倍的数额?

rlcwz9us  于 2023-11-15  发布在  Java
关注(0)|答案(1)|浏览(106)
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的25,然后平均值是50

rmbxnbpk

rmbxnbpk1#

建议:

  • 如果你想要一个更快的答案,分享一个可运行的代码。
  • 总是修改你的代码,它会更容易阅读。
  • 变量的名称非常重要,所以请给予一个合适的名称,以了解它们包含的内容。(例如,您声明了一个变量“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();
    }
    
}

字符串

相关问题