-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPortfolio.java
More file actions
98 lines (74 loc) · 2.59 KB
/
Copy pathPortfolio.java
File metadata and controls
98 lines (74 loc) · 2.59 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Portfolio {
private HashMap<String, Integer> holdings;
// Constructor
public Portfolio() {
holdings = new HashMap<>();
}
// Add shares after buying
public void addStock(String symbol, int quantity) {
holdings.put(
symbol,
holdings.getOrDefault(symbol, 0) + quantity
);
}
// Remove shares after selling
public boolean removeStock(String symbol, int quantity) {
int currentQuantity = holdings.getOrDefault(symbol, 0);
if (currentQuantity < quantity) {
return false;
}
int remaining = currentQuantity - quantity;
if (remaining == 0) {
holdings.remove(symbol);
} else {
holdings.put(symbol, remaining);
}
return true;
}
// Get number of shares owned
public int getQuantity(String symbol) {
return holdings.getOrDefault(symbol, 0);
}
// Check if portfolio is empty
public boolean isEmpty() {
return holdings.isEmpty();
}
// Display portfolio
public void displayPortfolio(ArrayList<Stock> stocks) {
if (holdings.isEmpty()) {
System.out.println("Your portfolio is empty.");
return;
}
System.out.println("\n============== MY PORTFOLIO ==============");
System.out.printf("%-10s %-15s %-10s %-15s%n",
"Symbol", "Company", "Quantity", "Value");
System.out.println("------------------------------------------");
double totalValue = 0;
for (Map.Entry<String, Integer> entry : holdings.entrySet()) {
String symbol = entry.getKey();
int quantity = entry.getValue();
for (Stock stock : stocks) {
if (stock.getSymbol().equalsIgnoreCase(symbol)) {
double value = quantity * stock.getPrice();
totalValue += value;
System.out.printf(
"%-10s %-15s %-10d ₹%.2f%n",
symbol,
stock.getName(),
quantity,
value
);
break;
}
}
}
System.out.println("------------------------------------------");
System.out.printf("Total Portfolio Value: ₹%.2f%n", totalValue);
System.out.println("==========================================");
}
}