關于 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)
2016-06-05
你是沒寫testForEach()方法