java显示最终解决方案,显示小数点后2位
我正在写一个程序,询问用户的年龄和他们拥有的钱的数量。如果他们已成年,他们将收到确认信息。如果他们不是,他们将被拒绝,他们剩下的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.");
}
}
}
# 1 楼答案
您可以使用以下语句:
# 2 楼答案
以前有人问过这个问题,谷歌搜索“java格式十进制货币”会显示
Java - format double value as dollar amount
你可以使用字符串。使用格式字符串格式化,也可以使用DecimalFormat类或NumberFormat类