2015-10-01 44 views
0

我正在编写一个程序,询问用户他们的年龄和他们拥有的金额。如果他们年龄大了,他们会收到确认信息。如果不是,他们将被拒绝,他们剩下的年数将会显示为21。钱也一样。啤酒5美元。如果用户没有足够多,它会告诉他们他们需要多少钱。但是......我无法生成在响应中显示2个小数位的值。我如何以美元金额或(例如1.00)而非1.0的形式显示解决方案或他们需要多少钱?显示最终解决方案并显示2位小数

//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

的可能的复制[Java的货币数字格式(http://stackoverflow.com/questions/2379221/java-currency-number-format) –

回答

1

您可以使用下面的语句:

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

这已经被问过,作为谷歌搜索“Java的格式小数钱”会显示...

Java - format double value as dollar amount

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