-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBudgetTracker.java
More file actions
73 lines (61 loc) · 2.64 KB
/
BudgetTracker.java
File metadata and controls
73 lines (61 loc) · 2.64 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.util.Scanner;
public class BudgetTracker {
public static void main(String[] args) {
final int MAX_ENTRIES = 15;
Scanner scanner = new Scanner(System.in);
// Declare and allocate arrays for item names and monetary values
String[] itemNames = new String[MAX_ENTRIES];
float[] itemValues = new float[MAX_ENTRIES];
// Initialize entry count
int entryCount = 0;
// Loop to get user input for budget items
do {
System.out.print("Enter a negative or positive value for a budget item. Enter 0 to stop: ");
float value = scanner.nextFloat();
scanner.nextLine(); // Consume newline character
if (value != 0 && entryCount < MAX_ENTRIES) {
System.out.print("Enter the name of the budget item: ");
String itemName = scanner.nextLine();
// Save values in arrays
itemValues[entryCount] = value;
itemNames[entryCount] = itemName;
entryCount++;
} else {
break;
}
} while (entryCount < MAX_ENTRIES);
// Calculate the maximum number of digits for dollars and cents
int maxDollars = 0;
int maxCents = 0;
for (int i = 0; i < entryCount; i++) {
String[] parts = String.format("%.2f", Math.abs(itemValues[i])).split("\\.");
maxDollars = Math.max(maxDollars, parts[0].length());
maxCents = Math.max(maxCents, parts[1].length());
}
// Print budget items and values
System.out.println("\nBudget Items:");
for (int i = 0; i < entryCount; i++) {
printBudgetItem(itemNames[i], itemValues[i], maxDollars, maxCents);
}
// Print total
float total = calculateTotal(itemValues, entryCount);
System.out.printf("\nTotal Budget: $%0" + (maxDollars + maxCents + 3) + ".2f\n", total);
scanner.close();
}
// Method to format and print each budget item
private static void printBudgetItem(String itemName, float value, int maxDollars, int maxCents) {
if (value < 0) {
System.out.printf("%-20s:($%0" + (maxDollars + maxCents + 3) + ".2f)\n", itemName, Math.abs(value));
} else {
System.out.printf("%-20s: $%0" + (maxDollars + maxCents + 3) + ".2f\n", itemName, value);
}
}
// Method to calculate the total of budget item values
private static float calculateTotal(float[] values, int count) {
float total = 0;
for (int i = 0; i < count; i++) {
total += values[i];
}
return total;
}
}