在存储用户输入之前检查退出程序

时间:2013-04-01 20:31:06

标签: java do-while bufferedwriter

我有一个近乎完成的程序。唯一的问题是当用户进入“退出”以终止程序时,单词“exit”将被写入文件“quotes.txt”的末尾。如何让程序首先检查“退出”而不是将其写入“quotes.txt”?

以下是代码:

public static void main(String[] args) throws IOException {

    final Formatter fo;
    BufferedWriter bw = null;
    BufferedReader in = new BufferedReader(new FileReader("quotes.txt"));
    String input = "";
    String line;

    File quotesFile = new File("quotes.txt");

    if (quotesFile.exists()) {
        System.out.println(quotesFile.getName() + " exists.");
    } else {
        System.out.println("THIS DOES NOT EXIST.");
    }

    try {
        fo = new Formatter("quotes.txt");
        System.out.println("File created or found.");

    } catch (Exception e) {
        System.out.println("You have an error.");
    }

    do {
        try {
            Scanner kb = new Scanner(System.in);

            if (!input.equalsIgnoreCase("exit")) {

                System.out.println("Enter your text(Type 'exit' to close program.): ");
                bw = new BufferedWriter(new FileWriter(quotesFile, true));
                input = kb.nextLine();
                bw.write(input);
                bw.newLine();
                bw.close();
                System.out.println("Entry added.\n");
            }

        } catch (Exception e) {
            System.out.println("Error.");
        }
    } while (!input.equalsIgnoreCase("exit"));

    System.out.println("Results: ");

    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }

}
}

2 个答案:

答案 0 :(得分:2)

您只能将您的扫描仪和编写器实例化一次。问题的关键是你在测试后检查输入。请注意,您复制了测试:if中的一个,while中的另一个。我建议你这个算法:

Scanner kb = new Scanner(System.in);
input = kb.nextLine();

while (!input.equalsIgnoreCase("exit")) {
    try {
        System.out.println("Enter your text(Type 'exit' to close program.): ");
        bw = new BufferedWriter(new FileWriter(quotesFile, true));
        bw.write(input);
        bw.newLine();
        bw.close();
        System.out.println("Entry added.\n");
    } catch (Exception e) {
        System.out.println("Error.");
    }
    input = kb.nextLine();
}

请注意,do...while不能最好地满足您的需求。

答案 1 :(得分:1)

在将输入写入文件之前检查输入是什么。

            System.out.println("Enter your text(Type 'exit' to close program.): ");
            bw = new BufferedWriter(new FileWriter(quotesFile, true));
            input = kb.nextLine();
            if(!input.equalsIgnoreCase("exit")) {
                bw.write(input);
                bw.newLine();
                bw.close();
                System.out.println("Entry added.\n");
            }
       }