Sentinel不能在Java循环中工作;和printwriter不写入文本文件

时间:2017-02-07 07:24:35

标签: java printwriter sentinel

UIActivityViewController

目前我的输出将无休止地要求我输入字符串'dataInput.txt'(位于相应的项目文件夹中),但它不会从适当的Java字符串标识符退出while循环。我在这里错过了什么吗?我没有使用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(); } } } 。 “-1”什么也没做,只能再循环回来。 踢出,以预先添加的方式将输入写入文本文件,然后关闭文件。

另外!事实证明,没有任何东西从while循环输入中获取并传输到'dataInput.txt'文件。我不确定为什么。

任何帮助将不胜感激!

编辑:就像一个FYI,我必须使用带有哨兵的while循环。再次感谢在这个问题上帮助我的每个人。

编辑#2:考虑到MadProgrammer的优秀建议,我在输出中留下了一个小问题:

==

正如您所看到的,它只接收两个对象,它们是“Goliath”和“Samson”,它们是写入文本文件的唯一字符串。从技术上讲,它应该有4个对象,“David”和“Delilah”应该也在文本文件中,但它们不是。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

while(!(sentinel.equals("-1")))永远不会是false(对于循环条件),因为sentinel永远不会改变,它总是""

从概念上讲,您需要阅读用户输入并决定如何使用它,然后使用此值来确定是否需要退出循环

所以,这是一个非常快速的"你可以做什么的例子(未经测试)...

Scanner input = new Scanner(System.in);
int i = 0;
try (FileOutputStream fos = new FileOutputStream("dataInput.txt", true)) {
    try (PrintWriter pw = new PrintWriter(fos)) {
        String userInput = "";
        do {
            userInput = input.nextLine();
            if (!userInput.equals("-1")) {
                pw.print(input.nextLine());
                i++;
            }
        } while (!userInput.equals("-1"));
    }
} 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);
}

仅供参考:input.close();并未关闭"文件",它关闭标准输入,这绝不是一个好主意

注意:复合try-with块是过度的,您可以使用单个语句将其全部包装起来,但我想展示围绕类似代码结构的概念