问答详情
源自:4-9 学生选课---应用泛型管理课程 Ⅰ

为啥报错呀

import java.util.ArrayList;

import java.util.List;


public class TestGeneric {


//带有泛型---Course的List类属性

public List<Course> course;

private ArrayList<Course> courses;

public TestGeneric(){

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

}

public void testAdd() {

Course cr1 = new Course("1","大学语文");

courses.add(cr1);

//泛型集合中,不能添加泛型规定的类型以外的对象,否则会报错

//courses.add("我是乱入的哈!");

Course cr2 = new Course("2","Java基础");

courses.add(cr2);

}

//通过foreach方法访问集合元素

public void testForEach() {

for(Course cr:courses) {

System.out.println("课程-->" + cr.id + ":" + cr.name);

}

public static void main(String[] args) {

TestGeneric tg = new TestGeneric();

tg.testAdd();

tg.testForEach();

}


}


Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

Syntax error, insert "}" to complete Block


at com.collection.TestGeneric.testForEach(TestGeneric.java:26)

at com.collection.TestGeneric.main(TestGeneric.java:31)


提问者:梦云云梦 2018-10-09 17:12

个回答

  • qq_雪影霜魂_0
    2018-10-09 22:01:23

    public void testForEach() {

    for(Course cr:courses) {

    System.out.println("课程-->" + cr.id + ":" + cr.name);

    }

    缺了一个大括号}