坚持循环找到总和和平均值

时间:2015-11-07 03:01:43

标签: java loops for-loop

这是我第二次使用堆栈溢出,我刚刚开始编码。

写一个名为Assignment4a的班级,提示用户输入学生人数,然后要求他们输入这些学生的考试成绩。然后,您的课程将计算并打印课程的总和和平均考试成绩。

import java.util.Scanner; 

public class Homework5A { 
   public static void main (String[]args) {
      Scanner kbd = new Scanner(System.in);

      String student;
      int grades = 0;
      double sum = 0;
      double avg = 0;

      for(int i=1; i<=grades; i++) {
         System.out.println("How many students?" );
         student= kbd.nextLine();
         System.out.println("Enter " + student + " grades: ");
         grades= kbd.nextInt();
         System.out.print("Sum: " + sum);
         sum = sum + grades; 
         }

      System.out.println("Average " + sum/students);



   }
}

2 个答案:

答案 0 :(得分:1)

 for(int i=1; i<=grades; i++) {}

您无法初始化从1开始并在0结束的for循环语句(因为当前成绩= 0)。

答案 1 :(得分:1)

试试这个

 import java.util.Scanner;

  import java.util.Scanner; 
   public class Test {

   public static void main (String[]args) {
      Scanner kbd = new Scanner(System.in);

      int student;
      int grades = 0;
      double sum = 0;
      double avg = 0;

      System.out.println("How many students?" );
         student= kbd.nextInt();
         System.out.println("Enter " + student + " grades: ");
      for(int i=0; i<student; i++) {
         grades= kbd.nextInt();
         sum = sum + grades; 
         System.out.println("Sum: " + sum);
         }

      System.out.println("Average " + sum/student);



   }
}

`