关于 It.testForEach();方法报错
package com.imocc.collection;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
public class ListTest {
//用于存放备选课程的List
public java.util.List coursesToSelect; //cousesToSelect是List数组的名字
public ListTest(){ //主类的构造方法
this.coursesToSelect = new ArrayList();//用于往coursesToSelect中添加备选课程
}
public void testAdd() {
Course cr1 = new Course("1","数据结构"); //还没有创建这个类
coursesToSelect.add(cr1);
Course temp = (Course)coursesToSelect.get(0);
System.out.println("添加了课程"+temp.id+":"+temp.name);
Course cr2 = new Course("2","C语言"); //还没有创建这个类
coursesToSelect.add(0,cr2); //怎么和上面的不一样?是由两个add方法吗?
Course temp2 = (Course)coursesToSelect.get(0);
System.out.println("添加了课程"+temp2.id+":"+temp2.name);
Course[] course = {new Course("3","离散数学"),new Course("4","汇编语言")};
coursesToSelect.addAll(Arrays.asList(course));
Course temp3 = (Course)coursesToSelect.get(2);
Course temp4 = (Course)coursesToSelect.get(3);
System.out.println("添加了两门课程:"+temp3.id +":"+ temp3.name+
";"+temp4.id + ":" + temp4.name);
Course[] course2 = {new Course("5","高等数学"),new Course("6","大学英语")};
coursesToSelect.addAll(2,Arrays.asList(course2));
Course temp5 = (Course)coursesToSelect.get(2);
Course temp6 = (Course)coursesToSelect.get(3);
System.out.println("添加了两门课程:"+temp5.id +":"+ temp5.name+
";"+temp6.id + ":" + temp6.name);
}
/**
* 取得List中元素的方法
* @param args
*/
public void testGet(){
int size = coursesToSelect.size();
System.out.println("有如下课程待选:");
for (int i = 0;i < size;i++){
Course cr = (Course)coursesToSelect.get(i);
System.out.println("课程:"+ cr.id + ":"+ cr.name);
}
}
/*
* 通过迭代器来遍历List
*/
public void testIterator() {
Iterator it = coursesToSelect.iterator();
System.out.println("有如下课程待选(通过for each访问):");
while(it.hasNext()){
Course cr = (Course) it.next();
System.out.println("课程:"+cr.id+":"+cr.name);
}
}
//修改List中元素
public void testModify(){
coursesToSelect.set(4,new Course("7","毛概"));
}
public static void main(String[] args) {
ListTest It = new ListTest();
It.testAdd(); //想添加课程但是在ListTest中没有这个方法!
It.testGet();
It.testIterator();
It.testForEach();
It.testModify();
It.testForEach();
}
编译的时候出现以下错误信息:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method testForEach() is undefined for the type ListTest
The method testForEach() is undefined for the type ListTest
Syntax error, insert "}" to complete ClassBody
at com.imocc.collection.ListTest.main(ListTest.java:87)