【发布时间】:2019-08-01 23:14:00
【问题描述】:
我目前正在开发一个旨在为汽车经销商存储库存的程序。当用户被提示使用 y/n 选项“您想将库存打印到文件中吗?(y/n)”时,我正在尝试找到将存储在数组列表中的数据打印到文件的正确方法。
到目前为止,我有两种不同的方法。一种显示我输入到数组中的数据,另一种将数据打印到文件中。我只需要弄清楚如何将问题和打印到文件方面添加到显示方法。
// method to save vehicle data to a file upon exiting the program
public static void printToFile(String filename) throws FileNotFoundException {
PrintWriter pw = new PrintWriter(filename);
String text = " Make | Model| Color| Year| Mileage\n";
for (Automobile a : carList) {
text += a.toCSV() + "\n"; // Separating car information with commas
}
pw.write(text);
pw.flush();
pw.close();
System.out.println("\n Car Inventory below has been printed to " + filename + " file. \n");
System.out.println(text);
}
// My method to display the data however I just need to find a way to incorporate the y/n question for printing to a file also
public static void displayCars() { // method to display all vehicles in the list
Scanner scnr = new Scanner(System.in);
System.out.println("--------------");
System.out.println("Car Inventory");
System.out.println("--------------");
for (Automobile a : carList) {
System.out.println(a + "\n");
// FIND OUT HOW TO ADD y/n INPUT FOR PRINTING TO FILE
}
}
希望在 Display 方法中添加一个 y/n 问题,询问用户是否要将数据打印到文件中。
【问题讨论】:
标签: java file input output printwriter