import java.io.*;import java.util.*;class Coures{ String id;String name; public Coures(String id,String name){ this.id = id; this.name = name; }}public class Test { public List<Coures> Coureslist = null; public Test(){ Coureslist = new ArrayList<Coures>(); } String s = null; int i = 0; File f = new File("word.txt"); public void Addcoures(){ try { FileReader fr = new FileReader(f); BufferedReader bur = new BufferedReader(fr); while((s=bur.readLine())!=null){ i++; System.out.println("第"+i+"行"+s); String str[] =s.split(";"); Coures co = new Coures(str[0],str[1]); Coureslist.add(co); } System.out.println("有"+Coureslist.size()+"門課程"); bur.close(); fr.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void testIterator(){//迭代器 Iterator<Coures> it = Coureslist.iterator(); System.out.println("有如下課程了"); while(it.hasNext()){ Coures cr = (Coures)it.next(); System.out.println("課程:"+cr.id+":"+cr.name); } } public static void main(String[] args) { new Test().Addcoures(); System.out.println("****************************************************"); new BufferedTest().testIterator(); }}上面是代碼 ?Word.txt文件中的內容如下:1;英語2;語文3;數學運行程序后迭代器輸出Coureslist是空的 ,在Addcoures()方法中添加System.out.println("有"+Coureslist.size()+"門課程");語句測試顯示Coureslist.size()等于3.請問這是什么原因了,怎樣才能讓迭代器輸出Coureslist內容???
1 回答
已采納

botao555
TA貢獻48條經驗 獲得超46個贊
public?static?void?main(String[]?args)?{ Test?test?=?new?Test(); test.Addcoures(); System.out.println("****************************************************"); test.testIterator(); }
main方法改成這樣試試,你調用Addcoures()方法時new了一個Test對象,此時Coureslist里被正常賦值,但是你調用testIterator()時又new了一個Test對象,所以testIterator()里時Coureslist里并沒有值。你應該只new一個Test對象,然后用這個對象分別調用Addcoures()和testIterator()就行了
解決了問題的話望采納!
添加回答
舉報
0/150
提交
取消