-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShoppingCart.java
More file actions
73 lines (64 loc) · 2.71 KB
/
ShoppingCart.java
File metadata and controls
73 lines (64 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* ShoppingCart
*
* ShoppingCart is the interface in which a customer can store and view products to check out.
* It creates a file for the certain user to act as storage to be saved. This file can be read
* from to add and delete products.
*/
public class ShoppingCart {
public String username;
public String password;
//Constructor for the ShoppingCart
public ShoppingCart(String username, String password) {
this.username = username;
this.password = password;
}
public void createCart() throws IOException {
// This method creates a new shopping cart file for each unique username
File file = new File("shoppingCart." + username + ".txt");
BufferedWriter newCart = new BufferedWriter(new FileWriter(file));
//file.createNewFile();
newCart.close();
}
//This method adds a product to the user's cart and creates a file named after them with
//some characteristics of the product, like the store, name of product, quantity bought, and price.
void addToCart(String store, String product, int quantity, double price) throws IOException {
PrintWriter pw = new PrintWriter(new FileWriter("shoppingCart." + username + ".txt", true), true);
pw.write(store + ";" + product + ";" + quantity + ";" + price);
pw.println();
pw.close();
}
//This method will remove an item from the user's shoppingCart
void removeFromCart(String store, String product, int quantity, double price) throws IOException {
String remove = String.format("%s;%s;%d;%f", store, product, quantity, price);
File tempFile = new File("myTempFile.txt");
File inFile = new File("shoppingCart." + username + ".txt");
BufferedReader br = new BufferedReader(new FileReader(inFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(tempFile));
String line;
while((line = br.readLine()) != null) {
String trimmedLine = line.trim();
if(!trimmedLine.equals(remove)) {
bw.write(line + System.getProperty("line.separator"));
}
}
bw.close();
br.close();
inFile.delete();
tempFile.renameTo(inFile);
}
//This returns a String array of the user's shopping cart.
public String [] getCart() throws IOException {
List<String> cart = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader("shoppingCart." + username + ".txt"));
String line;
while ((line = br.readLine()) != null) {
cart.add(line);
}
return cart.toArray(new String[0]);
}
//end of the class
}