【问题标题】:for loop structurefor循环结构
【发布时间】:2010-07-11 15:55:04
【问题描述】:

该程序将通过提示使用 for 循环计算 4 门考试的平均成绩 考试成绩的用户,一次一个,然后计算平均值并显示结果。

public class ExamsFor4 {

public static void main(String[] arguments) {


int inputNumber; // One of the exams input by the user.
int sum = 0;     // The sum of the exams.
int i;       // Number of exams.
Double Avg;      // The average of the exams.

TextIO.put("Please enter the first exam: ");        // get the first exam.
inputNumber = TextIO.getlnInt();    

for ( i = 1; i <= 4; i++ ) {  

    sum += inputNumber;                 // Add inputNumber to running sum.
    TextIO.put("Please enter the next exam: ");     // get the next exam.   
    inputNumber = TextIO.getlnInt();

        if (i == 4) {
            Avg = ((double)sum) / i;
            TextIO.putln();
            TextIO.putln("The total sum for all " + i +" exams is " + sum);
            TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
            break;

        }
} 

}   // end main ()
}  // end class ExamsFor4

我的结果:

Please enter the first exam: 100
Please enter the next exam: 99
Please enter the next exam: 98
Please enter the next exam: 97
Please enter the next exam: 96
The total sum for all 4 exams is 394
The average for the exams entered is 98.50.

这将是正确的,除了最后一个打印输出:'Please enter the next exam: 96' 我尝试将 IF 语句放在“sum”行和TextIO.put 'Enter next exam' 之间,但这会将其隔离。

感谢,来自程序员世界中的网络老兄陷阱。

【问题讨论】:

  • 这是你应该努力解决的事情类型,要么自己解决,要么失败。我很高兴我在学校时没有将堆栈溢出作为资源。

标签: java


【解决方案1】:

您遇到了所谓的逐一错误,再加上您不必要地对循环逻辑进行卷积。

关于循环,我推荐两件事:

  • 不要循环for (int i = 1; i &lt;= N; i++);这是非典型的
    • for (int i = 0; i &lt; N; i++);比较典型
  • 不要检查最后一次迭代来做某事,而是重构并将其置于循环之外

相关问题

另见


开启Double Avg

在 Java 中,变量名以小写字母开头。此外,Double 是一个引用类型,即原始 double 的框。只要有可能,你应该更喜欢double 而不是Double

另见

相关问题


重写

这是一种重写代码使其更具可读性的方法。我使用java.util.Scanner,因为我不认为TextIO 是标准的,但本质保持不变。

import java.util.*;

public class ExamsFor4 {
    public static void main(String[] arguments) {
        Scanner sc = new Scanner(System.in);
        final int NUM_EXAMS = 4;
        int sum = 0;

        for (int i = 0; i < NUM_EXAMS; i++) {
            System.out.printf("Please enter the %s exam: ",
                (i == 0) ? "first" : "next"
            );
            sum += sc.nextInt();
        }
        System.out.printf("Total is %d%n", sum);
        System.out.printf("Average is %1.2f%n", ((double) sum) / NUM_EXAMS);
    }
}

一个示例会话如下:

Please enter the first exam: 4
Please enter the next exam: 5
Please enter the next exam: 7
Please enter the next exam: 9
Total is 25
Average is 6.25

注意:

  • 只声明必要的变量
    • 循环索引仅在循环本地
  • 没有杂乱无章的 cmets
    • 相反,应专注于编写清晰、简洁、易读的代码
  • 如果做某事final 有意义,那就去做吧
    • Java 中的常量都是大写的

相关问题

【讨论】:

    【解决方案2】:

    将结束条件更改为严格小于 4,并将打印出总和平均值的代码放在循环之外。

    【讨论】:

      【解决方案3】:

      您可能应该将 if 语句放在 for 循环之外。这样你就不需要 if 语句。其次,循环中的语句应该是

      public class ExamsFor4 {
      
      public static void main(String[] arguments) {
      
      
      int inputNumber; // One of the exams input by the user.
      int sum = 0;     // The sum of the exams.
      int i;       // Number of exams.
      Double Avg;      // The average of the exams.
      
      TextIO.put("Please enter the first exam: ");        // get the first exam.
      inputNumber = TextIO.getlnInt();    
      
      for ( i = 1; i < 4; i++ ) {  
      
          sum += inputNumber;                 // Add inputNumber to running sum.
          TextIO.put("Please enter the next exam: ");     // get the next exam.   
          inputNumber = TextIO.getlnInt();
      } 
      
      Avg = ((double)sum) / i;
      TextIO.putln();
      TextIO.putln("The total sum for all " + i +" exams is " + sum);
      TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
      break;
      
      }   // end main ()
      }
      

      【讨论】:

      • 这样更干净但结果都一样?
      • 不,我错了。它现在似乎在 4 个条目后正确停止,但最后一个条目不会被添加到总和中。仍在与一次性错误作斗争。
      • 我必须在循环之前删除要求输入的行。 for (i = 0; i
      • 此代码不会将最后一个inputNumber 添加到sum
      【解决方案4】:

      只需对代码进行一些更改即可使其正常工作。但是您应该遵循一些答案中提出的更简洁的方法。

      public class ExamsFor4 {
      
        public static void main(String[] arguments) {
          int inputNumber; // One of the exams input by the user.
          int sum = 0;     // The sum of the exams.
          int i;       // Number of exams.
          double Avg;      // The average of the exams.
      
          TextIO.put("Please enter the first exam: ");        // get the first exam.
          inputNumber = TextIO.getlnInt();    
          sum += inputNumber;
      
          for ( i = 1; i < 4; i++ ) {  
      
            TextIO.put("Please enter the next exam: ");     // get the next exam.   
            inputNumber = TextIO.getlnInt();
            sum += inputNumber;                 // Add inputNumber to running sum.
      
          } 
      
          Avg = ((double)sum) / i;
          TextIO.putln();
          TextIO.putln("The total sum for all " + i +" exams is " + sum);
          TextIO.putf("The average for the exams entered is %1.2f.\n", Avg);
      
        }   // end main ()
      }  // end class ExamsFor4
      

      【讨论】:

        【解决方案5】:
        import java.util.Scanner;
        public class ExamsFor4 {
        
        public static void main(String[] arguments) {
        
            int sum = 0; // The sum of the exams.
            int i = 1; // Number of exams.
            double avg = 0; // The average of the exams.
        
            Scanner in = new Scanner(System.in);
            System.out.print("Please enter the first exam: ");
            sum += in.nextInt();
            i++;
            while(i<=4){
                System.out.print("Please enter the next exam: ");
                sum += in.nextInt();
                if(i==4)
                    break;// this line is so that it wont increment an extra time.
                i++;
            }
            System.out.println("The total sum for all " + i +" exams is " + sum);
            avg = ((double)sum/i);
            System.out.println("The average for the exams entered is" + avg);
        } // end main ()
        } // end class ExamsFor4
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多