简体   繁体   English

Sentinel在Java while循环中不起作用; 和printwriter不写入文本文件

[英]Sentinel not working in Java while-loop; and printwriter not writing to text file

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();
        }
    }
}

Currently my output will endlessly ask me to enter strings to 'dataInput.txt' (which is in the appropriate project folder) but it will not exit from the while loop with the proper sentinel for Java strings . 当前,我的输出将无休止地要求我向'dataInput.txt'(在适当的项目文件夹中)输入字符串,但是它不会从while循环中退出,并带有用于Java字符串适当标记 Am I missing something here? 我在这里想念什么吗? I'm not using == . 我没有使用== "-1" does nothing but loop back again. “ -1”什么也没做,只是再次循环。 It should kick out, write the inputs to the text file in prepending fashion and then close the file. 应该踢出,以前置方式将输入内容写入文本文件,然后关闭该文件。

Also! 也! As it turns out, nothing is being taken from the while-loop input and transferred to the 'dataInput.txt' file. 事实证明,while循环输入中没有任何内容被传输到“ dataInput.txt”文件中。 I'm not sure why. 我不知道为什么。

Any help will be greatly appreciated! 任何帮助将不胜感激!

EDIT: Just as an FYI, I must use a while loop with a sentinel. 编辑:就像供参考,我必须与哨兵一起使用while循环。 Thanks again everyone who is/has/will help me on this issue. 再次感谢每个/已经/将在这个问题上帮助我的人。

EDIT #2: Taking into account MadProgrammer's excellent advice, I'm left with one tiny problem left in my output: 编辑#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)

As you can see, it takes in only TWO objects they are "Goliath" and "Samson" and they are the only strings written to the text file. 如您所见,它仅接受两个对象,即“ Goliath”和“ Samson”,并且它们是唯一写入文本文件的字符串。 Technically it should have 4 objects and "David" and "Delilah" should be in the text file also, but they're not. 从技术上讲,它应该有4个对象,“ David”和“ Delilah” 应在文本文件中,但实际上不是。

Any help would be greatly appreciated. 任何帮助将不胜感激。

while(!(sentinel.equals("-1"))) can never be false (for the loop condition), because sentinel never changes, it's always "" while(!(sentinel.equals("-1")))永远不会为false (对于循环条件),因为sentinel永远不会改变,因此始终为""

Conceptually, you need to read the user input and decide what do with it, you would then use this value to determine if you need to exit the loop 从概念上讲,您需要阅读用户输入并决定如何处理,然后使用该值确定是否需要退出循环

So, this is a "really quick" example (not tested) of what you could do... 因此,这是您可以做的“非常快速”的示例(未经测试)...

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);
}

FYI: input.close(); 仅供参考: input.close(); isn't closing the "file", it's closing the stdin, which is never a good idea 不是关闭“文件”,而是关闭标准输入,这从来都不是一个好主意

NB: The compounding try-with blocks are overkill, you could use a single statement to wrap it all up in, but I wanted to demonstrate the concept around a similar code structure 注意:复合的try-with块是过大的,您可以使用一条语句将其包装起来,但是我想围绕类似的代码结构来演示该概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM