我需要创建一个对象清单,我可以在打印到txt文件之前添加,删除和修改这些对象。需要帮助!我不确定我是否以正确的方式设置了对象,或者它是否需要是一个数组。我有一本书,但它没有提到我需要的对象程序。
这是我的车辆对象
package PortfolioProject;
public class Vehicle {
// Variables
private String make;
private String model;
private String color;
private int year;
private int mileage;
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
}
这是使用对象的程序
package PortfolioProject;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Inventory {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Vehicle automobile = new Vehicle();
System.out.print("Make?");
String inMake = scan.nextLine();
automobile.setMake(inMake);
System.out.print("Model?");
String inModel = scan.nextLine();
automobile.setModel(inModel);
System.out.print("Color?");
String inColor = scan.nextLine();
automobile.setColor(inColor);
System.out.print("Year?");
int inYear = scan.nextInt();
automobile.setYear(inYear);
System.out.print("Mileage?");
int inMileage = scan.nextInt();
automobile.setMileage(inMileage);
File file = new File("output.txt");
// write to file
try {
PrintWriter output = new PrintWriter(file);
output.println("Make: " + automobile.getMake());
output.println("Model: " + automobile.getModel());
output.println("Color: " + automobile.getColor());
output.println("Year: " + automobile.getYear());
output.println("Mileage: " + automobile.getMileage());
output.close();
} catch (IOException ex) {
System.out.printf("ERROR: %s\n", ex);
}
scan.close();
}
}
答案 0 :(得分:0)
在写入文件之前,您可以使用automobile
检查vales是否来自对象(system.out
):
System.out.println(automobile.getMake());
如果没有显示任何值,您就会知道该问题与类或对象有关。否则,您可以通过PrintWriter
了解该问题。
检查完程序后,我注意到没有在output.txt
中写入值的原因:
不写任何值的原因:
File file = new File("output.txt");
仅保存文本文件的路径。如果文件不存在,PrintWriter
没有创建文件。 read about PrintWriter
<强>解决方案:强>
首先添加存在文本文件的目录,如下所示:
File file = new File("folder/output.txt");
然后您可以通过以下方式确保该目录是否存在:
file.getParentFile().mkdirs();
所有在一起:
File file = new File("folder/output.txt");
file.getParentFile().mkdirs();
// write to file
try {
PrintWriter output = new PrintWriter(file);
output.println("Make: " + automobile.getMake());
output.println("Model: " + automobile.getModel());
output.println("Color: " + automobile.getColor());
output.println("Year: " + automobile.getYear());
output.println("Mileage: " + automobile.getMileage());
output.close();
} catch (IOException ex) {
System.out.printf("ERROR: %s\n", ex);
}