你们都。我对基本Java有疑问。
因此,我一直在尝试找出如何从Controller类输入产品的数据,以及如何使用DataOutputStream将数据保存在文本文件中。产品类别已封装。但是我收到一些语法错误。如果有人可以帮助我,将不胜感激。
public class DataStream {
Product[] product = new Product[5];
Scanner sc = new Scanner(System.in);
public void productList() {
for(int i=0; i<4; i++) {
product[i] = new Product();
System.out.println("Input a product name");
String name = product[i].setName(sc.nextLine());
System.out.println("Input a price");
int price =product[i].setPrice(sc.nextInt());
System.out.println("Input a product quantity");
int quantity =product[i].setQuantity(sc.nextInt());
System.out.println("Input a product discount");
double discount =product[i].setDiscount();
}
}
public void addFile() {
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream("product.dat"));
dos.writeUTF(product.getName());
dos.writeInt(product.getPrice());
dos.writeInt(product.getQuantity());
dos.writeDouble(product.getDiscount());
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
dos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void printFile() {
DataInputStream dis = null;
try {
dis = new DataInputStream(new FileInputStream("product.dat"));
dis.readUTF(); dis.readInt(); dis.readDouble();
System.out.println(product);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
dis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}