0

我有一个几乎完成的程序。唯一的问题是当用户输入“exit”来杀死程序时,“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);
    }

}
}
4

2 回答 2

2

你只能实例化你的 Scanner 和 writer 一次。问题的关键是你在测试后检查输入。请注意,您重复了测试:一个在 中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不要最好地响应您的需求。

于 2013-04-01T20:42:26.190 回答
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");
            }
       }
于 2013-04-01T20:34:47.053 回答