为什么我无法加入到已选课程中,courses中没有添加到课程

来源:4-11 学生选课---通过 Set 集合管理课程

慕侠6582840

2016-09-24 00:23

package com.imooc.collection;



import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

import java.util.Scanner;


public class SetTest {

public List<Course> courseToSelect;

public SetTest(){

courseToSelect=new ArrayList<Course>();

}

public void testAdd(){

// 创建一个课程对象,并通过调用add方法,添加调用add方法,添加到备选课程;List中

Course cr1=new Course("1.","数据结构"); 

courseToSelect.add(cr1);

Course temp=(Course) courseToSelect.get(0);

// System.out.println(temp.id+temp.name);

Course cr2=new Course("2.","C语言");

courseToSelect.add(1,cr2);

Course temp2=(Course) courseToSelect.get(1);

// System.out.println(temp2.id+temp2.name);

Course[] cr3={new Course("3.","离散数学"),new Course("4.","汇编语言")};

courseToSelect.addAll(Arrays.asList(cr3));

Course temp3=(Course) courseToSelect.get(2);

Course temp4=(Course) courseToSelect.get(3);

// System.out.println(temp3.id+temp3.name+temp4.id+temp4.name);

Course[] cr4={new Course("5.","算法"),new Course("6.","大学英语")};

courseToSelect.addAll(0,Arrays.asList(cr4));

Course temp5=(Course) courseToSelect.get(4);

Course temp6=(Course) courseToSelect.get(5);

// System.out.println(temp5.id+temp5.name+temp6.id+temp6.name);

}

public void foreach(){

System.out.println("foreach");

for(Course cr:courseToSelect){

System.out.println(cr.id+cr.name);

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub

SetTest st=new SetTest();

st.testAdd();

st.foreach();

Student student=new Student("1","小米");

System.out.println("欢迎"+student.name+"选课");

Scanner console=new Scanner(System.in);

for(int i=0;i<3;i++){

System.out.println("输入课程ID");

String courseId=console.next();

for(Course cr:st.courseToSelect){

if(cr.id.equals(courseId)){

student.courses.add(cr);

}

}

}

st.tesx(student);

System.out.println(student.courses.size());

}

public void tesx(Student student){

for(Course cr:student.courses){

System.out.println(cr.id+cr.name);

}

}

}



//学生类

package com.imooc.collection;

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;

        this.courses = new HashSet<Course>();

    }

}


//Course 类

package com.imooc.collection;


public class Course {

 

    public String id;

     

    public String name;

     

    public Course(String id, String name) {

        this.id = id ;

         

        this.name = name;

    }

     

    public Course() {

         

    }

}


写回答 关注

1回答

  • ziom
    2016-09-24 07:03:05
    已采纳

    testAdd()里面添加的Course的id都是"1.", "2."....所以你在输入课程ID的时候也要输入数字加"."的方式才能使cr.id.equals(courseId)

    慕侠6582...

    非常感谢!

    2016-09-24 22:47:43

    共 3 条回复 >

Java入门第三季

Java中你必须懂得常用技能,不容错过的精彩,快来加入吧

409792 学习 · 4340 问题

查看课程

相似问题