Budget analysis

The problem

Write a program that asks the user to enter the amount that he or she has budgeted for a month. A loop should then prompt the user to enter each of his or her expenses for the month, and keep a running total. When the loop finishes, the program should display the amount that the user is over or under budget.

Breaking it down

public static void main(String[] args) {

    // Create a DecimalFormat object to format output.
    DecimalFormat dollar = new DecimalFormat("#,##0.00");

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    // Get the budget amount.
    System.out.print("Enter your budget for the month: ");
    double monthlyBudget = keyboard.nextDouble();

    // Get each expense, keep track of total.
    double expense;
    double totalExpenses = 0.0;
    do {
        // Get an expense amount.
        System.out.print("Enter an expense, or a negative "
                + "number to quit: ");
        expense = keyboard.nextDouble();

        totalExpenses += expense;

    } while (expense >= 0);

    // Display the amount after expenses.
    double balance = calculateAmountOverBudget(monthlyBudget, totalExpenses);
    if (balance < 0) {
        System.out.println("You are OVER budget by $"
                + dollar.format(Math.abs(balance)));
    } else if (balance > 0) {
        System.out.println("You are UNDER budget by $"
                + dollar.format(balance));
    } else {
        System.out.println("You spent the budget amount exactly.");
    }

    keyboard.close();
}

static double calculateAmountOverBudget(double monthlyBudget,
        double totalExpenses) {
    return monthlyBudget - totalExpenses;
}

Output

Enter your budget for the month: 100
Enter an expense, or a negative number to quit: 10
Enter an expense, or a negative number to quit: 10
Enter an expense, or a negative number to quit: 10
Enter an expense, or a negative number to quit: 10
Enter an expense, or a negative number to quit: 10
Enter an expense, or a negative number to quit: -10
You are UNDER budget by $60.00

Level Up

  • Refactor the budget attributes into an object to represent an Budget. Use a constructor to set the variables and getters to get the values.
  • There is a bug in the program when trying to quit, what is it?