|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.List; |
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +class Expense { |
| 6 | + private String description; |
| 7 | + private double amount; |
| 8 | + |
| 9 | + public Expense(String description, double amount) { |
| 10 | + this.description = description; |
| 11 | + this.amount = amount; |
| 12 | + } |
| 13 | + |
| 14 | + public String getDescription() { |
| 15 | + return description; |
| 16 | + } |
| 17 | + |
| 18 | + public double getAmount() { |
| 19 | + return amount; |
| 20 | + } |
| 21 | + |
| 22 | + @Override |
| 23 | + public String toString() { |
| 24 | + return "Description: " + description + ", Amount: $" + amount; |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +public class ExpenseTracker { |
| 29 | + public static void main(String[] args) { |
| 30 | + Scanner scanner = new Scanner(System.in); |
| 31 | + List<Expense> expenses = new ArrayList<>(); |
| 32 | + double totalExpenses = 0.0; |
| 33 | + |
| 34 | + while (true) { |
| 35 | + System.out.println("Expense Tracker Menu:"); |
| 36 | + System.out.println("1. Add an expense"); |
| 37 | + System.out.println("2. View expenses"); |
| 38 | + System.out.println("3. Exit"); |
| 39 | + System.out.print("Select an option (1/2/3): "); |
| 40 | + |
| 41 | + int option = scanner.nextInt(); |
| 42 | + |
| 43 | + switch (option) { |
| 44 | + case 1: |
| 45 | + scanner.nextLine(); // Consume the newline character |
| 46 | + System.out.print("Enter expense description: "); |
| 47 | + String description = scanner.nextLine(); |
| 48 | + System.out.print("Enter expense amount: $"); |
| 49 | + double amount = scanner.nextDouble(); |
| 50 | + expenses.add(new Expense(description, amount)); |
| 51 | + totalExpenses += amount; |
| 52 | + System.out.println("Expense added successfully."); |
| 53 | + break; |
| 54 | + case 2: |
| 55 | + if (expenses.isEmpty()) { |
| 56 | + System.out.println("No expenses recorded yet."); |
| 57 | + } else { |
| 58 | + System.out.println("List of Expenses:"); |
| 59 | + for (Expense expense : expenses) { |
| 60 | + System.out.println(expense); |
| 61 | + } |
| 62 | + System.out.println("Total Expenses: $" + totalExpenses); |
| 63 | + } |
| 64 | + break; |
| 65 | + case 3: |
| 66 | + System.out.println("Exiting the Expense Tracker."); |
| 67 | + scanner.close(); |
| 68 | + System.exit(0); |
| 69 | + default: |
| 70 | + System.out.println("Invalid option. Please select 1, 2, or 3."); |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments