我和我父亲将其范围缩小到无法存储数据的对象。另外,我是java的新手。该代码应在控制台中打印名字,姓氏,成绩和平均成绩。我认为问题出在公共double getCalcGraeAverage()中,但是如果出错请纠正我。

import java.util.Scanner;
/**
 * Write a description of class Student here.
 *
 * @author XXXX
 * @version XXXX
 */
public class Student
{
    String firstName;
    String lastName;
    int gradeLevel;
    double gradeAverage;
    int totalAssignments;
    double totalPoints;

      /**
     * Create a new student with student's name, grade, and average
     */
    public Student(String newFirstName, String newLastName, int newGradeLevel, double newGradeAverage)
    {
        firstName = newFirstName;
        lastName = newLastName;
        gradeLevel = newGradeLevel;
        gradeAverage = newGradeAverage = 0.0;
    }

      /**
     * Return the student's first name.
     */
    public String getFirstName()
    {
        return firstName;
    }

      /**
     * Return the student's last name.
     */
    public String getLastName()
    {
        return lastName;
    }

      /**
     * Return the grade level of the student.
     */
    public int getGradeLevel()
    {
        return gradeLevel;
    }

         /**
     * Calculates grade average.
     */
    public double getCalcGradeAverage()
    {

       double gradeAverage = totalAssignments / totalPoints;
       return gradeAverage;
    }

    public static void main (String[] args)
    {
        Student student1 = new Student ("XXXX", "XXXX", 11, 0.0);

        System.out.println("The student's first name is: " + student1.getFirstName());
        System.out.println("The student's last name is: " + student1.getLastName());
        System.out.println("The student's grade level is: " + student1.getGradeLevel());

        System.out.println("Please enter the total assignment points the student has earned: ");

        Scanner input = new Scanner(System.in);
        Double totalAssignments  = input.nextDouble();

        System.out.println("Please enter the number of assignments given: ");

        double totalpoints  = input.nextDouble();

        System.out.println(student1.getFirstName() + " " + student1.getLastName() +  " average grade is" + student1.getCalcGradeAverage());
    }
}

最佳答案

在您的代码中,您是:


创建一个Student student1对象
totalAssignments读取totalpointsSystem.in
呼叫student1.getCalcGradeAverage()


在第2步和第3步之间,必须将totalAssignmentstotalpointsstudent字段设置为您读取的值,否则它们将保留其默认值零。例如。

student1.totalAssignments = totalAssignments;
student1.totalpoints = totalpoints;


另外,由于totalAssignments的类型为int,因此您可能希望将其读取为:

int totalAssignments  = input.nextInt();

10-05 21:41