1、完成书上84页实验题第2题。
个人答案:
public class Course {
private String courseName; //课程名
private int creditHour; //学分
public Course() {
super();
/*super关键字 */
}
public Course(String courseName, int creditHour) {//学科名称和学分
super();
this.courseName = courseName;
this.creditHour = creditHour;
}
public String getCourseName() {//得到学科名称的方法
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public int getCreditHour() {//得到学科学分的方法
return creditHour;
}
public void setCreditHour(int creditHour) {
this.creditHour = creditHour;
}
}
public class Student {
private String stuName;
private int grade;
private Course[] courses; //学生选择的多门课程
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String stuName, int grade, Course[] courses) {//学生的姓名年级和所选学科
super();
this.stuName = stuName;
this.grade = grade;
this.courses = courses;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public Course[] getCourses() {
return courses;
}
public void setCourses(Course[] courses) {
this.courses = courses;
}
public int getHours(){//总学分
int sum=0;
for(int i=0; i<courses.length; i++){
sum+= courses[i].getCreditHour();
}
return sum;
}
public void show(){ //学生总信息
System.out.println(stuName+" "+ grade+"grade ");
System.out.println("Elective courses include:");
for(int i=0; i<courses.length; i++){
System.out.println("("+(i+1)+"}"+courses[i].getCourseName()+ "\t" + courses[i].getCreditHour());
}
System.out.println("Total credits:"+getHours());
}
}
import java.util.Scanner;
public class text { //测试函数
public static void main(String[] args) {
System.out.print("Enter the number of students:");//学生个数
try (Scanner scn = new Scanner(System.in)) {
int number = scn.nextInt();
Student[] stu = new Student[number];
for(int i=0; i<stu.length; i++){
Student s = new Student();
stu[i]=s;
System.out.print("Enter the name of the "+(i+1)+"th student:");//学生姓名
String name = scn.next();
s.setStuName(name);//调用方法
System.out.print("Enter the grade of the "+(i+1)+"th student:");//年级
int grade=scn.nextInt();
s.setGrade(grade);
System.out.print("Enter the number of courses selected by the "+(i+1)+"th student:");//选择科目个数
int numCourse= scn.nextInt();
Course[] courses= new Course[numCourse];
stu[i].setCourses(courses);
for(int j=0; j<courses.length; j++){
courses[j] = new Course();
System.out.print("Enter the name of the "+(j+1)+"th course:");//科目名称
String courseName = scn.next();
courses[j].setCourseName(courseName);
System.out.print("Enter credits for the "+(j+1)+"th course:");//科目学分
int creditHour = scn.nextInt();
courses[j].setCreditHour(creditHour);
}
}
for(int i=0; i<stu.length; i++){
System.out.println("The information of the "+(i+1)+"th student is as follows:");//该同学的信息
stu[i].show();
System.out.println();
}
}
}
}