gpt4 book ai didi

java - While 循环覆盖其他输入

转载 作者:行者123 更新时间:2023-12-01 21:26:40 24 4
gpt4 key购买 nike

每当我将输入放入此循环中时,无论有多少,它都只会将我的最终输入写入文件代码如下:

import java.util.Scanner;
import java.io.IOException;
import java.io.*;

class lista {
public static void main(String[] args) throws IOException {
Scanner n = new Scanner(System.in);
int x = 0;
File productList = new File("productList.txt");
FileWriter fr = new FileWriter("productList.txt", true);

/// While Loop Start

while (x == 0) {
System.out.println("Enter the product:");
String product = n.nextLine();
System.out.println("");
System.out.println("Enter the price:");
String price = n.nextLine();
System.out.println("");
System.out.println("Enter the type of product, e.g. Movie, Bluray, etc...");
String type = n.nextLine();
System.out.println("");
System.out.println(product + " - " + "$" + price + " (" + type + ")" + "\n\n");
try {
fr.write((product + " - " + "$" + price + " (" + type + ")" + "\n\n"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Type \"0\" if you would like to stop, type \"1\" if you would like to continue.");
int y = n.nextInt();
n.nextLine();
if (y == 1) {
x = 0;
} else {
x = 1;
fr.close();
}
}
/// While Loop Ends

}
}

我可以输入类似的内容,1,1,1,12,2,2,13,3,3,0,它只会打印:

3 - $3 (3)

谢谢。

最佳答案

这可能是 Trouble with filewriter overwriting files instead of appending to the end 的重复项。然而,您似乎已经自己找到了解决方案(创建 FileWriter 时的 true 参数)。这应该附加到文件而不是覆盖它。如果这不起作用,则文件或操作系统可能有问题。无论如何,您的代码从根本上来说并没有错误,应该可以工作。

关于代码本身的可读性和易用性的一些建议(只是次要细节)。

Scanner in = new Scanner(System.in);
PrintStream out = System.out;

try (FileWriter writer = new FileWriter("productList.txt", true)) {
INPUT_LOOP:
while (true) {
out.println("Enter the product:");
String product = in.nextLine();
out.println();

out.println("Enter the price:");
String price = in.nextLine();
out.println();

out.println("Enter the type of product, e.g. Movie, Bluray, etc...");
String type = in.nextLine();
out.println();

String entry = product + " - " + "$" + price + " (" + type + ")" + "\n\n";
out.println(entry);
writer.append(entry);

out.println("Type \"exit\" if you would like to stop, any other input will continue.");
if (in.nextLine().trim().toLowerCase().equals("exit")) {
break INPUT_LOOP;
}
}
} catch (IOException e) {
e.printStackTrace();
}

关于java - While 循环覆盖其他输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58828330/

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