简体   繁体   English

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

[英]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. 如果不是,它们将被拒绝,并且将显示剩余的年数为21。 Same goes for the money. 钱也一样。 It is 5 dollars for a beer. 一杯啤酒5美元。 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. 但是...我无法生成一个在响应中显示2个小数位的值。 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? 如何显示解决方案,或者他们需要多少钱(以美元金额或(例如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.");
        }
}
}

This has been asked before, as a google search for "java format decimal money" would show... 之前有人问过这个问题,因为Google搜索“ java格式的十进制货币”会显示...

Java - format double value as dollar amount Java-将双精度值格式化为美元金额

You can use String.Format with a format string, or you can use the DecimalFormat class, or the NumberFormat class. 您可以将String.Format与格式字符串一起使用,也可以使用DecimalFormat类或NumberFormat类。

您可以使用以下语句:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM