我想创建一个名为“Course”的对象,并从键盘获取信息。最后一个属性称为“pre”,表示本课程的必修课程。我想在一行中输入整个信息并提取每个属性的信息。但是我遇到了“pre”的问题。我运行程序,course.pre的输出为null。我不知道为什么。这是我的课程类代码: `import java.util.HashSet;
公共课程{
private String name;
private int isFall;
private int NumPre;
private HashSet<Course> pre;
public Course(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String setName (String n){
return name = n;
}
// 1 - fall 0 - both -1 - spring
public void setType(String isFall) {
if(isFall.equals("F") || isFall.equals("f")){
this.isFall = 1;
}else if(isFall.equals("S") || isFall.equals("s")){
this.isFall = -1;
}else if(isFall.equals("B") || isFall.equals("b")){
this.isFall = 0;
}
}
public int getType(){
return isFall;
}
public void SetNumPre(int n) {
this.NumPre = n;
}
public int getNumPre() {
return NumPre;
}
public void addPre(Course c) {
pre.add(c);
}
public HashSet<Course> getPre() {
return pre;
}
} ` 这是我的主要方法:
import java.util.*;
公共课TimeToGraduate {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
//System.out.print("Input first two integers here: ");
String globalInfo = scanner.nextLine();
String[] numOfCourse = globalInfo.split(" ");//[0] num of total course [1] max num per semester
int totalNum = Integer.parseInt(numOfCourse[0]);
int maxPre = Integer.parseInt(numOfCourse[1]);
Course courses[] = new Course[totalNum];
//System.out.print("Please input course list here: ");
String coursesList = scanner.nextLine();
String[] nameOfCourse = coursesList.split(" ");
for(int i = 0;i < totalNum; i++){
courses[i] = new Course(nameOfCourse[i]);
}
//System.out.print("Please input course info here: ");
for(int i = 0;i < totalNum; i++){
String courseInfo = scanner.nextLine();
String[] infoOfCourse = courseInfo.split(" ");
courses[i].setName(infoOfCourse[0]);
courses[i].setType(infoOfCourse[1]);
courses[i].SetNumPre(Integer.parseInt(infoOfCourse[2]));
if(courses[i].getNumPre() > 0){
for(int j = 3; j < 3+(courses[i].getNumPre()); j++){
for(int k = 0; k < totalNum; k++){
if(infoOfCourse[j] == courses[k].getName()){
courses[i].addPre(courses[k]);
}
}
}
}
}
scanner.close();
for(int m = 0; m < totalNum; m++){
System.out.print(courses[m].getName()+" ");
System.out.print(courses[m].getType()+" ");
System.out.print(courses[m].getNumPre()+" ");
System.out.print(courses[m].getPre()+" ");
System.out.println();
}
}
}
答案 0 :(得分:0)
请注意,您没有初始化pre属性。这就是它为空的原因。
如果您在Course类的构造函数中初始化pre,那将是一个很好的做法。否则,在开始填充“课程”属性时执行此操作。
你的构造函数应该是这样的:
public Course() { this.pre = new HashSet()}
正如您所看到的,构造函数没有任何争论,因为您将从main函数填充其属性。
您也可以使用参数定义构造函数:
public Course(String name, HashSet<Course> pre)
{ this.name = name; this.pre = pre; }
但是当您从主要部门调用它时,您需要初始化pre和name:
...
HashSet hs = new HashSet();
course[i] = new Course('course_name', hs);
....