2013-09-24 166 views
-3

我有一個關於PrintWriter的Java中的問題,這裏是我的代碼:PrintWriter的混亂

import java.io.File; 
    import java.io.FileNotFoundException; 
    import java.io.PrintWriter; 
    import java.util.Scanner; 


public class Out { 

public static void main(String[] args) { 

    try{ 
File a=new File("C:/Users/Acer/Desktop/abc.txt"); 
PrintWriter out=new PrintWriter(a); 
Scanner c=new Scanner(System.in); 


while(c.hasNextInt()){ 
    out.printf("%d", c.nextInt()); 
    out.println(); 
c.close(); 
} 
out.close(); 
System.out.println("input written into file successfully!"); 
    } 
    catch(FileNotFoundException e){ 
System.out.println("The file not found"); 


    } 
} 

    } 

我運行該程序後,文件ABC的內容丟失,然後我進行掃描功能輸入1 2 3 4 5,它示出了誤差修改:

1 2 3 4 5 
    Exception in thread "main" java.lang.IllegalStateException: Scanner closed 
at java.util.Scanner.ensureOpen(Unknown Source) 
at java.util.Scanner.hasNext(Unknown Source) 
at java.util.Scanner.hasNextInt(Unknown Source) 
at java.util.Scanner.hasNextInt(Unknown Source) 
at Out.main(Out.java:17) 

它應該輸出:

 1 
    2 
    3 
    4 
    5 

但似乎在PR沒有找到該文件,我不確定哪個部分是錯誤的,請幫助,歡呼!

+0

爲什麼他們做投票嗎? – user2705620

回答

2

您正在致電hasNextInt()方法在關閉Scanner對象c,給你execption。

所以c.close();外應while

+0

你好,謝謝你的幫助,是的,似乎錯誤信息已經消失,但是當我輸入1 2 3 4 5時,它根本沒有反應,我應該期待什麼結果? –

+0

@WangPeiTheDancer爲了得到響應,你需要輸入一個非整數值,以便它從循環中退出。例如輸入爲'1 2 3 4 5 h' – Prabhaker

+1

@WangPeiTheDancer add out.flush();在你的循環中,每次循環迭代都會在文件中打印數據 – JohnnyAW

1

您關閉循環本身中的Scanner對象!

試着把它放在循環之外。

while(c.hasNextInt()){ 
    out.printf("%d", c.nextInt()); 
    out.println(); 
} 
c.close(); 

你預期的輸出結果是:

input written into file successfully! 

而不是:

1 
2 
3 
4 
5 
0

試試這個

while(c.hasNextInt()){ 
out.printf("%d", c.nextInt()); 
out.println(); 
} 
c.close();