【发布时间】:2017-02-07 17:00:31
【问题描述】:
package addlinenumbers;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class AddLineNumbers {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String sentinel = new String();
int i=0;
try
{
FileOutputStream fos = new FileOutputStream
("dataInput.txt", true); //true means we will be appending to dataInput.txt
PrintWriter pw = new PrintWriter (fos);
//write data to the file
while(!(sentinel.equals("-1")))
{
System.out.println("Please enter strings to prepend to 'dataInput.txt'; -1 to EXIT: ");
pw.print(input.nextLine());
i++;
}
}
catch (FileNotFoundException fnfe)
{
System.out.println("Unable to find dataInput.txt...");
}
catch (IOException ioe)
{
ioe.printStackTrace(System.out);
}
finally
{
System.out.println("# of objects: " + i);
System.out.println("Closing file...");
input.close();
}
}
}
目前,我的输出将无休止地要求我将字符串输入到“dataInput.txt”(位于相应的项目文件夹中),但它不会使用 Java 字符串的正确哨兵退出 while 循环。我在这里错过了什么吗?我没有使用==。 "-1" 什么都不做,只是再次循环。 它应该退出,以前置方式将输入写入文本文件,然后关闭文件。
还有!事实证明,没有从 while 循环输入中获取任何内容并传输到“dataInput.txt”文件中。我不知道为什么。
任何帮助将不胜感激!
编辑:仅供参考,我必须使用带有哨兵的 while 循环。再次感谢所有/已经/将在这个问题上帮助我的人。
编辑 #2:考虑到 MadProgrammer 的出色建议,我在输出中留下了一个小问题:
run:
Please enter strings to prepend to 'dataInput.txt'; -1 to EXIT:
David
Goliath
Please enter strings to prepend to 'dataInput.txt'; -1 to EXIT:
Delilah
Samson
Please enter strings to prepend to 'dataInput.txt'; -1 to EXIT:
-1
# of objects prepended: 2
Closing file...
BUILD SUCCESSFUL (total time: 18 seconds)
如您所见,它只接收两个对象,它们是“Goliath”和“Samson”,它们是写入文本文件的唯一字符串。从技术上讲,它应该有 4 个对象,并且“David”和“Delilah”应该也在文本文件中,但它们不是。
任何帮助将不胜感激。
【问题讨论】:
-
你永远不会在你的循环中更新
sentinel,所以它永远不会改变 -
“还有!事实证明,没有从 while 循环输入中获取任何内容并传输到 'dataInput.txt' 文件。我不知道为什么。” i> 可能是因为蒸汽从不关闭
-
看看try-with-resources,它会让你的生活更轻松
-
为什么哨兵需要更新?它是一个固定字符串,等于除“-1”之外的所有内容?另外..我将如何“更新”它?你提出了一个有趣的提示。谢谢先生。
-
实际上是一个空字符串,或者
""。但你明白了。您需要做的是将输入存储在变量中。例如,sentinel = input.nextLine(); pw.print(sentinel);尽管正如您所指出的,sentinel不是这个变量的好名字。
标签: java printwriter sentinel