-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStudentBudget2.java
More file actions
70 lines (64 loc) · 2.5 KB
/
StudentBudget2.java
File metadata and controls
70 lines (64 loc) · 2.5 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
import java.util.Scanner;
public class StudentBudget2 {
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;
boolean validInput = false;
// 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: ");
if (scanner.hasNextFloat()) {
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++;
validInput = true;
} else {
break;
}
} else {
System.out.print("Invalid Input");
break;
}
} while (entryCount < MAX_ENTRIES);
// Print budget items and values
// exit if invalid input
if (validInput) {
System.out.println("\nBudget Items:");
for (int i = 0; i < entryCount; i++) {
printBudgetItem(itemNames[i], itemValues[i]);
}
// Print total
float total = calculateTotal(itemValues, entryCount);
System.out.printf("\nTotal Budget: $%.2f\n", total);
}
scanner.close();
}
// Method to format and print each budget item
private static void printBudgetItem(String itemName, float value) {
// take value to string get length
if (value < 0) {
System.out.printf("%-20s: ($%.2f)\n", itemName, Math.abs(value));
} else {
System.out.printf("%-20s: $%.2f\n", itemName, value);
}
}
// Method to calculate the total of budget item values123
private static float calculateTotal(float[] values, int count) {
float total = 0;
for (int i = 0; i < count; i++) {
total += values[i];
}
return total;
}
}