扫描仪的平均等级

时间:2015-10-20 22:31:43

标签: java methods average

我遇到以下代码问题。我需要申请人询问用户的学生人数,然后询问每个年级。有了这个我必须找到平均值。这是我的代码到目前为止,我不知道如何解决它。

谢谢!

    import java.util.Scanner;

public class Assignment6 
{
    public static int students;
    public static int grade;
    public static int avg;
    public static int obtainStudents(){
        Scanner input = new Scanner(System.in);
        System.out.println("How many students");
        students = input.nextInt();
        return students;
        }

    public static double obtainGrade(int students){
        Scanner input = new Scanner(System.in);

            System.out.println("Enter Grade");
            grade = input.nextInt();
            grade+=grade;

        return grade;
    }
    public static double calculateClassAverage(){
        for(int i = 0; i<students; ++i){
            obtainGrade(students);
            System.out.println();
        }
        System.out.println();
        avg = grade / students;
    return avg;
    }


public static void main (String [] Args){
    obtainStudents();
    calculateClassAverage();
    System.out.println(avg);

}

}

2 个答案:

答案 0 :(得分:0)

grade = input.nextInt()取代累计总数 grade+=grade然后将值加倍。

<强>结果: grade总是等于最后输入成绩的两倍 avg = grade / students则表示avg = 2 * lastGrade / studentCount

答案 1 :(得分:0)

您的问题在于您将所有成绩合计以找到平均值。

public static double obtainGrade(int students){
    Scanner input = new Scanner(System.in);

        System.out.println("Enter Grade");
        //sets grade to input wiping all previous inputs
        grade = input.nextInt();
        //adds grade to itself again
        grade+=grade;

    return grade;
}

你应该做这样的事情

public static int totalGrade

public static double obtainGrade(int students){
    Scanner input = new Scanner(System.in);

        System.out.println("Enter Grade");
        grade = input.nextInt();
        totalGrade+=grade;

    return grade;
}

avg = totalGrade/students;