I'm writing a Java program where the user can add Product objects into a ShoppingCart ArrayList. I want to save the Product objects into a text file so that the ShoppingCart ArrayList can be accessed again later. I'm writing to text file because this is school work and I'm not allow to use external DBs.
I'm running into a problem where the writeCart() method doesn't write to file, the output file is empty.
case 6:
System.out.println("Find Product by name");
String name = Menu.scan.next();
Product p = Catalog.searchProduct(name);
if (p == null) {
System.out.println("Product not found");
} else {
System.out.println(p);
}
System.out.println("Would you like to add this item to your cart?");
System.out.println("1. Yes");
System.out.println("2. No");
option = Integer.parseInt(input.nextLine());
if (option == 1) {
cart.addLineItem(p);
System.out.println(cart);
}
Menu.menu();
option = Integer.parseInt(input.nextLine());
break;
case 7:
System.out.println(" Place Order for items in cart");
Order order = new Order(customer,cart);
cart.writeCart(fileName);
Menu.menu();
option = Integer.parseInt(input.nextLine());
break;
import java.util.*;
public class ShoppingCart {
private List <Product> ShoppingCart = new ArrayList<>();
public void addItem (Product product) {
boolean exists = false;
for (Product item: products) {
if (item.getName() == product.getName()) {
item.addQuantity(product.getQuantity());
exists = true;
}
}
if (!exists) {
ShoppingCart.add(product);
}
}
public void writeCart(String fileName) throws IOException {
PrintWriter pw = new PrintWriter(new FileWriter(fileName,true));
for (Product p: products) {
pw.println(p.getName()+"-"+p.getCat()+"-"+p.getPrice()+"-"+p.getQuantity());
}
}