为什么testForeach() 函数中 Course cr : student.courses 会报错?

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

Bye白夜

2017-07-05 15:20

package com.imooc.stu;

import java.util.ArrayList;
import java.util.List;
import java.util.*;

public class setTest {

	public List<Course> coursetoSelect;
	
	public setTest() {
		this.coursetoSelect = new ArrayList<Course>();	
	}

	public void crAdd(){
		
		Course[] cr = {new Course("1","语文"),new Course("2","数学"),new Course("3","英语"),new Course("4","物理"),new Course("5","生物")};
		
		coursetoSelect.addAll(Arrays.asList(cr));
		
	}
	
	
	public void crDisplay() {
		
		System.out.println("有如下待选课程:");
		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.crAdd();
		st.crDisplay();
		
		Student student = new Student("1","小明");
		System.out.println("欢迎学生:" + student.name);
		
		Scanner sc = new Scanner(System.in);
		
		for(int i = 0;i<3;i++){
			System.out.println("请输入选择课程ID:");
			String scc = sc.next();
			for(Course cr : st.coursetoSelect) {
				if(cr.id.equals(scc)) {
					student.courses.add(cr);
					
				}
			}
				
			
		}
		
		st.testForeach(student);

	}
	
	public void testForeach(Student student) {
		for(Course cr : student.courses){
			System.out.println(cr.id + "" + cr.name);
		}
		
	}
	

}


写回答 关注

1回答

  • Bye白夜
    2017-07-05 15:26:35
    package com.imooc.stu;
    import java.util.*;
    
    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>();
    		
    	}
    	
    }

    原来是Student类没有定义泛型  public Set<Course> courses;

Java入门第三季

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

409784 学习 · 4339 问题

查看课程

相似问题