gpt4 book ai didi

Java-对象不能存储数据

转载 作者:行者123 更新时间:2023-11-30 06:58:39 27 4
gpt4 key购买 nike

我和爸爸将范围缩小到对象无法存储数据。另外,我是java新手。该代码应该在控制台中打印名字、姓氏、成绩和平均成绩。我认为问题出在 public 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());
}
}

最佳答案

在您的代码中,您是:

  1. 创建一个学生student1对象
  2. System.in读取totalAssignmentstotalpoints
  3. 调用student1.getCalcGradeAverage()

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

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

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

int totalAssignments  = input.nextInt();

关于Java-对象不能存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41348993/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com