-3

我对 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 的内容丢失了,然后我执行 Scanner 功能输入 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

但是程序似乎找不到文件,我不确定哪个部分是错误的,请帮助,干杯!

4

3 回答 3

2

您正在对给您执行 hasNextInt()的封闭Scanner 对象调用方法。c

所以c.close();应该在while循环之外

于 2013-09-24T12:23:43.403 回答
1

您正在关闭Scanner循环本身内的对象!

试着把它放在循环之外。

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

您的预期输出是:

input written into file successfully!

并不是:

1
2
3
4
5
于 2013-09-24T12:24:35.083 回答
0

试试这个

while(c.hasNextInt()){
out.printf("%d", c.nextInt());
out.println();
}
 c.close();  
于 2013-09-24T12:25:29.760 回答