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文件中的內(nèi)容如下:1;英語(yǔ)2;語(yǔ)文3;數(shù)學(xué)運(yùn)行程序后迭代器輸出Coureslist是空的 ,在Addcoures()方法中添加System.out.println("有"+Coureslist.size()+"門課程");語(yǔ)句測(cè)試顯示Coureslist.size()等于3.請(qǐng)問(wèn)這是什么原因了,怎樣才能讓迭代器輸出Coureslist內(nèi)容???
1 回答
已采納

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