gpt4 book ai didi

java - 与其他类的数组 - 对象 - Java

转载 作者:行者123 更新时间:2023-12-01 06:45:51 25 4
gpt4 key购买 nike

我有 3 个类(class):CourseCourseEntryTranscript。在成绩单中,我有一个添加类(class)的功能,如下所示:

public class Transcript {
CourseEntry coursestaken[] = new CourseEntry[6];

public void addCourse(Course course)
{
coursestaken[lastIndexOf(getCoursestaken())] = new CourseEntry(course);
}
(lastIndexOf gives me the empty array index - it's working on)

在我的CourseEntry中:

public class CourseEntry {
Course course;
char grade = 'I';

public CourseEntry(Course course)
{
this.course = course;
}

在我的类(class)中:

public  class Course {
int courseNumber,credits;
String courseName;

public Course addNewCourse(int courseNumber, int credits, String courseName)
{
this.courseNumber = courseNumber;
this.credits = credits;
this.courseName = courseName;

return this;
}

在我的主要部分:

Transcript t = new Transcript();
Course course = new Course();

Course matematik = course.addNewCourse(1, 2, "Matematik");
t.addCourse(matematik);

Course turkce = course.addNewCourse(1, 4, "Türkçe");
t.addCourse(turkce);

但是如果我循环 coursetaken 数组,它会打印所有内容的最后插入索引。

我该如何解决这个问题?

谢谢

最佳答案

您需要为每个类(class)创建一个新的 Course 对象,您的 addNewCourse 方法只会改变当前的 Course 对象。像这样修改Course:

public class Course {
private final int courseNumber;
private final int credits;
private final String courseName;

public Course(int courseNumber, int credits, String courseName) {
this.courseNumber = courseNumber;
this.credits = credits;
this.courseName = courseName;
}

public int getCourseNumber() {
return courseNumber;
}

public int getCredits() {
return credits;
}

public String getCourseName() {
return courseName;
}
}

然后使用以下内容:

Transcript t = new Transcript();

Course matematik = new Course(1, 2, "Matematik");
t.addCourse(matematik);

Course turkce = new Course(1, 4, "Türkçe");
t.addCourse(turkce);

关于java - 与其他类的数组 - 对象 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14346818/

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