显示最终解决方案,显示2个小数位

时间:2015-10-01 19:13:46

标签: java jgrasp

我正在编写一个程序,询问用户的年龄和所拥有的金额。如果他们年龄大,他们会收到确认信息。如果他们不是,他们将被拒绝,并将显示他们留下的年数21。同样的钱。啤酒是5美元。如果用户没有足够的用户,它会告诉他们需要多少钱。但是......我无法生成一个在响应中显示2个小数位的值。如何以美元金额或(例如1.00)而不是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.");
        }
}
}

2 个答案:

答案 0 :(得分:1)

之前有人问过,谷歌搜索“java格式十进制货币”会显示......

Java - format double value as dollar amount

您可以将String.Format与格式字符串一起使用,也可以使用DecimalFormat类或NumberFormat类。

答案 1 :(得分:1)

您可以使用以下声明:

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