Java:在附加文本文件时跳过第一行用户输入?

时间:2016-02-09 20:55:33

标签: java java.util.scanner filewriter printwriter

因此,我尝试接受用户的文本行,以便将其附加到txt文件中。但是,程序运行后,用户输入的第一行不会出现在附加文件中。

以下是代码的一部分:

System.out.println("enter advice (hit return  on empty line to quit):");
String advice = keyboard.nextLine();

FileWriter fw = new FileWriter(inputFile, true);
PrintWriter pw = new PrintWriter(fw);

for(int n = 1; n <= 2; ++n)
{
  advice = keyboard.nextLine();
  pw.print(advice);
}

pw.close();
keyboard.close();

以下是代码的示例运行:

$ java Advice
enter input filename: Advice.txt **enter**
1: fully understand the given problem
2: do analysis and design first before typing
enter advice (hit return  on empty line to quit):
a **enter**
b **enter**

Thank you, goodbye!
$ cat Advice.txt
1: fully understand the given problem
2: do analysis and design first before typing
b

有什么想法? 谢谢!

1 个答案:

答案 0 :(得分:2)

正在捕获用户输入的第一行但未写入该文件。 String advice = keyboard.nextLine(); 当您写入文件时,您将接收下一个用户输入