Search code examples
javajgrasp

Display final solution with 2 decimal places displayed


I am writing a program that ask the user for their age and the amount of money they have. If they are of age they will receive a confirmation message. If they are not they will be denied and the amount of years they have left to be 21 will be displayed. Same goes for the money. It is 5 dollars for a beer. If the user doesn't have enough it will tell them how much they need. However... I can't produce a value that displays 2 decimal places in the response. How can I display the solution or how much money they need in the form of dollar amount or (ex. 1.00) instead of 1.0?

//import classes
import java.util.*;

public class beerLab
{
static Scanner console = new Scanner(System.in);

public static void main (String[] args)
{
    // Declares the price of beer and the age required to purchase beer.
    double beer = 5.00;
    double moneyGiven;
    int age = 21;
    int ageGiven;

    // Request the age from the client.
    System.out.println("Please type customer age: ");
    ageGiven = console.nextInt();

    if (ageGiven < 21)  // If the client is under 21 then their purchase will be denied.
        {
            System.out.println("No beer for you!" + "\n" + "Come back in " + (age - ageGiven) + " years" + "\n" + "Thank you for your patronage.");
            return;
        }

    // Request the the amount of money the client has.
    System.out.println("Type customer cash amount: ");
    moneyGiven = console.nextDouble();

    if (moneyGiven < beer)  // If the client doesn't provide enough money, the program will tell client how much money they need.
        {
          System.out.println("Sorry, you need " + (beer - moneyGiven) + " more." + "\n" + "Thank you for your patronage.");
        }

    if (ageGiven > 21 & moneyGiven >= beer)  // If the client is old enough and has enough money they can purchase the beer.
        {
            System.out.println("Congratulations, you can have some beer."  + "\n" + "Thank you for your patronage.");
        }
}
}

Solution

  • You may use the following statement:

    System.out.format("Sorry, you need %.2f more." + "\n" + "Thank you for your patronage.\n", beer - moneyGiven);