我有以下代码(我不是很懂电脑,所以要温和),用户应该能够输入单独的硬币金额,程序会告诉用户他们在所述硬币数量上有多少钱。
import java.util.*;
public class Coins {
public static final Scanner CONSOLE = new Scanner(System.in);
public static void main(String[] args) {
System.out.println ("Lab 2 by Maria T Williams\n");
quarterAmount( );
dimeAmount( );
nickelAmount( );
pennyAmount( );
}
public static void quarterAmount( ) {
System.out.print("Enter the number of quarters: ");
int quarterNumber = CONSOLE.nextInt( );
double amount = quarterNumber * 0.25;
System.out.print(quarterNumber + " You have $" + amount);
System.out.println(" worth of quarters.");
}
public static void dimeAmount( ) {
System.out.print("Enter the number of dimes: ");
int dimeNumber = CONSOLE.nextInt( );
double amount = dimeNumber * .10;
System.out.print(dimeNumber + " You have $" + amount);
System.out.println(" worth of dimes.");
}
public static void nickelAmount( ) {
System.out.print("Enter the number of nickels: ");
int nickelNumber = CONSOLE.nextInt( );
double amount = nickelNumber * 0.05;
System.out.print(nickelNumber + " You have $" + amount);
System.out.println(" worth of nickels.");
}
public static void pennyAmount( ) {
System.out.print("Enter the number of pennies: ");
int pennyNumber = CONSOLE.nextInt( );
double amount = pennyNumber * 0.01;
System.out.print(pennyNumber + " You have $" + amount);
System.out.println(" worth of pennies.");
}
}
如果我输入的数量在100s不是“0”的地方我很好。但是,如果我进入,比如两个季度,我会收回“0.5美元”而不是“0.50美元”。
答案 0 :(得分:1)
您可以使用DecimalFormat
强制将数字格式化为您喜欢的格式。 E.g:
DecimalFormat df = new DecimalFormat("#.00");
double amount = dimeNumber * .10;
System.out.print(dimeNumber + " You have $" + df.format(amount) + " worth of dimes.");
答案 1 :(得分:0)
输出计算结果时,您可以使用DecimalFormat
,如下所示:
DecimalFormat f = new DecimalFormat("#0.00");
System.out.println(f.format(dimeNumber));