gpt4 book ai didi

java - 多对多关系的面向对象方法

转载 作者:行者123 更新时间:2023-11-30 08:21:31 25 4
gpt4 key购买 nike

我目前正在努力了解如何以面向对象的方式解决这个问题。

对于多对多关系,例如学生-科目,其中每个学生都会获得某个科目的分数,假设如下:

我希望能够显示给定学生的所有分数。我想显示给定科目的不同学生的所有分数我希望能够更改给定科目的任何学生的分数。

我在最后一个问题上遇到了麻烦,我似乎想不出一种方法将类彼此关联起来,以便标记在更改时保持一致...

这是我想用伪代码做的事情。假设我们有 3 个学生,每个学生涉及 3 个科目(总共 9 分):

Make a class for Student (String name, int studNumber)

Make a class for Subject (String name, int subNumber)

Make a class for Result(int percentageScore String grade(calculated based on
percentageScore))

Then have an array of arrays of Result objects, eg. [1][2] in the array will
give the score for the student with studNumber 2 in the subject with subNumber 1.

我感觉这不是面向对象的?应该对学科和学生的类设计中的关系有某种认识。如果那确实是对的,那么有人能指出我正确的方向吗?如何以面向对象的方式做到这一点?

非常感谢。

最佳答案

为什么要使用如此复杂的类结构。您可以有一个简单的 Student class

  class Student{

String stuName;
long rollNo;

public Student(String stuName, long rollNo){
this.stuName=stuName;
this.rollNo=rollNo;
}
.
.
.

}

还有一个主题类。每个科目都有特定的学生注册,以及每个学生在该科目中的分数。可以表示为:-

class Subject{

String subName;
HashMap<Integer,Student> Result;

public Subject(String subName){
this.subName=subName;
Result=new HashMap<Integer,Student>();
}

//add methods to add students,modify marks, etc

public void addStudent(String name,long roll, int marks){


Result.put(marks,new Student(name,roll));

}

public int giveMarksForSubject(long roll){

//iterate Results , and check for student objects to match roll no. return key of matching student
.
.
.
}

.
.

}

对于您提到的部分,您希望为学生更改特定科目的分数。您可以在 Main 方法的类中按字符串名称搜索 Subject 对象,然后根据名称/rollNo 更改学生的分数。您可以在 Subject 类中提供方法来实现此类功能。

关于java - 多对多关系的面向对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25153370/

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