我有一個關於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沒有找到該文件,我不確定哪個部分是錯誤的,請幫助,歡呼!
爲什麼他們做投票嗎? – user2705620