import java.util.Scanner; import java.io。*;
公共类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();
}
答案 0 :(得分:3)
将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();
答案 1 :(得分:3)
您在循环的每次迭代中close
编写者answers
。
答案 2 :(得分:0)
在第一次循环之后,你正在关闭作家。循环完成后,在循环结束后移动answers.close();
关闭编写器。
答案 3 :(得分:0)
将answers.close();
移到循环之外。它应该可以正常工作。