导入java.util.Scanner; 导入java.io.*;
公共(public)类 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();
}
for 循环执行完所有 18 行后,它不会将我的任何答案写入“answers.txt”文件。我在这里做错了什么?谢谢
最佳答案
将 close
语句移出 for
循环,这样就不会在每次迭代中关闭 PrintWriter
。此外,您每次迭代都会从 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();
关于java - for 循环后输入未写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20021415/