gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:55:06 25 4
gpt4 key购买 nike

我有一个即将完成的程序。唯一的问题是,当用户输入“exit”来终止程序时,“exit”一词会被写入文件“quotes.txt”的末尾。如何让程序首先检查“exit”而不将其写入“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);
}

}
}

最佳答案

您只能实例化您的扫描仪和编写器一次。问题的关键在于你测试后检查输入。请注意,您重复了测试:一个在 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 并不能最好地满足您的需求。

关于java - 在存储用户输入之前检查退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15751319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com