[英]Input not getting written to a file after a for loop
import java.util.Scanner; 导入java.util.Scanner; import java.io.*;
导入java.io. *;
public class Kazarian_MadLibs { 公共课程Kazarian_MadLibs {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
File file = new File("Mad Libs 1.txt");
Scanner inputFile = new Scanner(file);
System.out.println("Please provide a word for each of the following: ");
PrintWriter answers = new PrintWriter("answers.txt");
inputFile.nextLine();
for (int i = 0; i < 18; i++)
{
System.out.println(inputFile.nextLine());
keyboard.next();
answers.println(keyboard.nextLine());
answers.close();
}
after the for loop has finished executing all 18 lines, it doesn't write any of my answers to the "answers.txt" file. 在for循环完成所有18行的执行之后,它没有将我的任何答案写入“ answers.txt”文件。 What am I doing wrong here?
我在这里做错了什么? Thanks
谢谢
Move the close
statement out of the for
loop so that you're not closing the PrintWriter
in each iteration. 将
close
语句移出for
循环,以免在每次迭代中都不关闭PrintWriter
。 Also you're reading from the Scanner
instance twice per iteration - just read the value once and write to file 另外,您每次迭代都从
Scanner
实例读取两次-只需读取一次值并写入文件
for (int i = 0; i < 18; i++) {
System.out.println(inputFile.nextLine());
String answer = keyboard.nextLine(); // Assign variable here
answers.println(answer);
}
answers.close();
您可以在循环的每次迭代中close
编写器answers
。
Afer the first run through the loop you are closing the writer. 在第一次运行循环后,您将关闭编写器。 Move the
answers.close();
移动
answers.close();
after the loop the close the writer after the loop has finished. 循环结束后,在循环结束后关闭编写器。
Move the answers.close();
移动
answers.close();
outside the loop.It should work fine then. 在循环之外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.