计算一个班级的平均值

时间:2015-11-08 16:46:36

标签: java class math methods average

现在我正在制作一个程序,打印出学生姓名,身份证号码,考试成绩,平均分数和成绩。由于某些原因,计算平均分数的方法存在问题。我试过添加括号,但也没有改变结果。这最终会影响成绩,因为成绩是用平均分来计算的。任何帮助表示赞赏,谢谢!这是我的代码:

 import java.util.Scanner;

    public class Student {
    private String fname;
    private String lname;
    private int id;
    private int score1;
    private int score2;
    private int score3;
    private double average;
    private String grade;

    public void readInfo()
    {
        Scanner k = null;
        k = new Scanner (System.in);

        System.out.println ("Please enter the first name: (Enter John as first name and Doe as last name to stop) ");
        fname = k.next();
        System.out.println("Please enter the last name: ");
        lname = k.next();
        if (fname.equalsIgnoreCase("John")&&lname.equalsIgnoreCase("Doe"))
            System.exit(0);
        System.out.println("Please enter the student ID: ");
        id = k.nextInt();
        System.out.println("Please enter the first score: ");
        score1 = k.nextInt();
        System.out.println("Please enter the second score: ");
        score2 = k.nextInt();
        System.out.println("Please enter the third score: ");
        score3 = k.nextInt();
    }

//The problem lies in here:

    private void computeAverage()
    {
        average = score1+score2+score3/3.0;

    }
    private void computeGrade()
    {
        if (average>=90&&average<=100)
            grade = "A";
        else if (average>=80&&average<=89.9)
            grade = "B";
        else if (average>=70&&average<=79.9)
            grade = "C";
        else if (average>=60&&average<=69.9)
            grade = "D";
        else 
            grade = "F";
    }

    private String getName()
    {
        return fname + " " + lname;
    }
    private double getAverage()
    {
        return average;
    }
    public void printAll()
    {
        System.out.printf("%-9s%-10s %-9s %-3s %-3s %-3s %-5s  %-5s", "LastName","FirstName","ID","S1","S2","S3","AVG","GRADE");
        System.out.println();
        System.out.println("-----------------------------------------------------");
        System.out.printf("%-9s%-9s  %-9d %-3d %-3d %-3d %-3.2f%-2s",lname,fname,id,score1,score2,score3,average,grade);
        System.out.println();
        System.out.println("-----------------------------------------------------");

    }

    }

2 个答案:

答案 0 :(得分:1)

  • 我想问题是因为,你没有初始化变量平均值
  • 但是,您有一个方法 computeAverage()。它没有在程序的任何地方调用。也许你也可以在外面的任何地方做这件事。
  • 请包括肯定会产生正确结果的括号。

答案 1 :(得分:0)

操作顺序。你正在做的是sum 1 + sum 2 加上 sum3和3的商。当你除以时,你必须除以完全你需要分割的东西。你应该做(sum 1+ sum 2+ sum 3)/3

如果你不想除以2,你也可以乘以一半,这不会改变任何东西,但它只是另一种选择。

  

(sum 1+ sum 2+ sum 3)*1/2

请记住您想要划分的内容。如果是更多术语,请利用分组符号!

{Rich}