Restaurant bill

The problem

Write a program that computes the tax and tip for a restaurant bill. User is to enter the total amount of the bill. Tax is 6.75% of the bill. The tip is 15% of the meal after tax has been added. The meal charge, tax, tip, and total should be printed on the screen.

Breaking it down

Create constants

private static double TAX_RATE = 0.0675;
private static double TIP_PERCENT = .15;

Initialize variables

double mealCharge; // To hold the meal charge
double tax; // To hold the amount of tax
double tip; // To hold the tip amount
double total; // To hold the total charge

Scanner keyboard = new Scanner(System.in);

Ask user for meal charge

System.out.print("Enter the charge for the meal: ");
mealCharge = keyboard.nextDouble();

Create supporting calculation methods

/**
 * Method should calculate tax based on meal charge and tax rate
 * @param mealCharge
 * @return
 */
static double calculateTax (double mealCharge) {
    return mealCharge * TAX_RATE;
}

/**
 * Method should calculate tip based on meal charge and tip %.
 * 
 * @param mealCharge
 * @return
 */
static double calculateTip (double mealCharge) {
    return mealCharge * TIP_PERCENT;
}

/**
 * Method should calculate total due based on method parameters.
 * 
 * @param mealCharge
 * @param tax
 * @param tip
 * @return
 */
static double calculateTotal (double mealCharge, double tax, double tip) {
    return mealCharge + tax + tip;
}

Calculate tax, tip and total

// Calculate the tax.
tax = calculateTax (mealCharge);

// Calculate the tip.
tip = calculateTip (mealCharge);

// Calculate the total.
total = calculateTotal (mealCharge, tax, tip);

Display results

System.out.println("Meal Charge: $" + mealCharge);
System.out.println("Tax:         $" + tax);
System.out.println("Tip:         $" + tip);
System.out.println("Total:       $" + total);

Output

Enter the charge for the meal: 75
Meal Charge: $75.0
Tax:         $5.0625
Tip:         $11.25
Total:       $91.3125

Unit tests

@Test
public void calculateTax() {
    double meal = 100;
    assertEquals(6.75, ResturantBill.calculateTax(meal), 0); 
}

@Test
public void calculateTip() {
    double meal = 100;
    assertEquals(15, ResturantBill.calculateTip(meal), 0);
}

@Test
public void calculateTotal() {
    double mealCharge = 100;
    double tax = 6.75;
    double tip = 15;
    assertEquals(121.75, ResturantBill.calculateTotal(mealCharge, tax, tip), 0); 
}

Level Up

  • Allow tax rate and tip to be inputed by user
  • Validate user input charge of the meal
  • Pretty up ouput
  • Tax rate is determined typically by state, create a Map to look up state tax. It would look something like key - "WI", value = .0675.