java While循环覆盖其他输入
每当我向这个循环中输入内容时,不管有多少,它都只会将我的最终输入写入文件 以下是代码:
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,1 2,2,2,1 3,3,3,0 ,它只会打印:
3 - $3 (3)
谢谢
# 1 楼答案
这可能是Trouble with filewriter overwriting files instead of appending to the end的重复。 不过,您似乎已经找到了解决方案(创建FileWriter时的
true
参数)。这应该附加到文件中,而不是覆盖它。如果这不起作用,那么您可能会遇到文件或操作系统的问题。在任何情况下,您的代码都不是根本错误,应该可以正常工作关于代码本身的可读性和易用性的一些建议(只是一些小细节)