这个是Course类:
package StudentCourseSystem;
import java.util.HashSet;
import java.util.Set;
public class Course {
public String id;
public String name;
public Set<Course> courses;
public Course(String id, String name) {
this.id = id;
this.name = name;
this.courses = new HashSet<Course>();
}
/*
* public Course() {
*
* }
*/
}
这个是Student类:
package StudentCourseSystem;
import java.util.HashSet;
import java.util.Set;
public class Student {
public String id;
public String name;
public Set<Course> courses;
public Student(String id, String name) {
this.id = id;
this.name = name;
courses = new HashSet<Course>();
}
}
这个是SetTest类:
package StudentCourseSystem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SetTest {
public List<Course> coursesToSelect;
public SetTest() {
coursesToSelect = new ArrayList<Course>();
}
public void testAdd() {
Course cr1 = new Course("1", "数据结构");
coursesToSelect.add(cr1);
Course temp = (Course) coursesToSelect.get(0);
Course cr2 = new Course("2", "JAVA入门");
coursesToSelect.add(0, cr2);
Course temp2 = (Course) coursesToSelect.get(0);
Course cr3 = new Course("3", "JSP");
coursesToSelect.add(cr3);
Course temp3 = (Course) coursesToSelect.get(2);
Course[] course = { new Course("4", "离散数学"), new Course("5", "HTML") };
coursesToSelect.addAll(Arrays.asList(course));
Course temp4 = (Course) coursesToSelect.get(3);
Course temp5 = (Course) coursesToSelect.get(4);
Course[] course2 = { new Course("5", "高等数学"), new Course("6", "大学物理") };
coursesToSelect.addAll(5, Arrays.asList(course2));
Course temp6 = (Course) coursesToSelect.get(5);
Course temp7 = (Course) coursesToSelect.get(6);
}
public void testForEach() {
System.out.println("总共有以下课程供选择");
for (Object obj : coursesToSelect) {
Course cr = (Course) obj;
System.out.println(cr.id + ":" + cr.name);
}
}
public void testForEachForSet(Student student) {
System.out.println("选课完成,您总共选择了以下几门课程");
for (Course cr : student.courses) {
System.out.println(cr.id + ":" + cr.name);
}
}
public static void main(String[] args) {
SetTest st = new SetTest();
Student student = new Student("1", "小明");
System.out.println("欢迎" + student.name + "同学选课");
Scanner console = new Scanner(System.in);
st.testAdd();
st.testForEach();
for (int i = 0; i < 3;) {
for (Course cr : st.coursesToSelect) {
System.out.println("请输入第" + (i + 1) + "门课程的id");
String courseId = console.next();
if (courseId.equals(cr.id)) {
student.courses.add(cr);
System.out.println("添加" + cr.name + "成功");
i++;
} else {
System.out.println("输入错误,请重新输入!");
continue;
}
}
}
st.testForEachForSet(student);
}
}
最终代码运行的效果就像上面那样提示说输入错误,这是怎么回事?
其他地方都没有问题,我觉得可能就是main方法里面的for循环是不是出了一些差错,求解答!
添加回答
举报
0/150
提交
取消