简体   繁体   English

尽管while循环中有条件,扫描器输入仍会附加到文本文件中

[英]Scanner input gets appended to textfile despite condition in while-loop

I have a small little Java application that, on Terminal execution, will take string inputs, and saves those strings to a text file. 我有一个小的Java应用程序,在终端执行时将接收字符串输入,并将这些字符串保存到文本文件中。 I have the string exit that would prompt the application to exit. 我有一个字符串exit ,它将提示应用程序退出。 However, for some reason, the string exit gets appended to the document despite having that while(!) loop. 但是,由于某种原因,尽管有while(!)循环,但字符串exit仍会附加到文档中。 What could be the issue? 可能是什么问题?

try{
            Scanner scanner = new Scanner(System.in);
            String input = null;
            while(!"exit".equalsIgnoreCase(input)){
                input = scanner.nextLine();
                String fileLocation = "/Users/myName/Dropbox/myDocument.txt";
                FileWriter writer = new FileWriter(fileLocation,true);

                writer.append(returnDate()+": ");
                writer.append(input + "\n");

                writer.flush();
                writer.close();
            }
        }catch(Exception e){
            e.printStackTrace();
        }

Follow your code mentally. 认真遵循您的代码。 You do all the processing in the loop, before the while loop condition is evaluated the next time through. 您需要在下一次评估while循环条件之前 ,在循环中进行所有处理。

You have: 你有:

while(!"exit".equalsIgnoreCase(input)){
    input = scanner.nextLine(); 
    ...
    writer.append(input + "\n");
    ...
}

Assuming the user types "exit" as the first command, the flow is: 假设用户键入“ exit”作为第一个命令,则流程为:

  1. input is null initially. 最初inputnull
  2. while condition succeeds. while条件成功。
  3. input is read, it is now "exit". 读取input ,现在是“退出”。
  4. input , ie "exit", is written to file. input (即“退出”)被写入文件。
  5. while loop restarts, condition is evaluated, fails, loop does not execute again. while循环重新开始,条件评估,失败,循环不会再次执行。

Note that "exit" was written to the file. 请注意,“退出”已写入文件。

You will have to rework your logic a bit to make sure that the file write does not occur. 您将需要稍微修改一下逻辑以确保不会发生文件写入。 This is not an uncommon type of situation. 这不是一种罕见的情况。 There are many solutions depending on your preference. 有许多解决方案取决于您的喜好。 You could combine the assignment and comparison into the while statement: 您可以将赋值和比较合并到while语句中:

while (!"exit".equalsIgnoreCase(input = scanner.nextLine())) {
    write input;
}

You could have a redundant check (doesn't make sense for your simple example and also frequently indicates room for overall logic improvement): 您可能会有多余的检查(对于您的简单示例而言,这没有意义,而且经常指示总体逻辑改进的空间):

while (input is not exit) { 
    read input;
    if (input is not exit) write input;
}

You could not use the loop condition at all: 您根本无法使用循环条件:

while (true) {
    read input; 
    if (input is exit) break;
    write input;
}

There are many ways to fix it. 有很多方法可以修复它。

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

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