转换货币单位

时间:2015-02-20 08:18:19

标签: java units-of-measurement

我得到了美元,但现在我无法弄清楚如何正确显示四分之一,硬币,硬币和便士。从技术上来说,他们出现了,但我的教授希望1.35美元显示为1美元1季度和1美分。但是,我的显示为1美元5个季度13个角钱27个镍币135便士。这是我的代码:

import java.util.Scanner;

public class ComputeChange {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter an amount in double, for example 11.56: " );
        double number = input.nextDouble();
        System.out.println("Your amount " + number + " consists of ");
        int remainingamount = (int)(number*100);
        int Quarters = remainingamount/25;
        int Dimes = remainingamount/10;
        int Nickels = remainingamount/5;
        int Pennies = remainingamount;

        if (number == 1) {
            System.out.print("1 dollar ");
        }
        else if (number > 1) {
            System.out.print((int)number + " dollars ");
        }
        if (number == 0) {
            System.out.println("");
        }
        System.out.print(Quarters + " Quarters " + Dimes + " Dimes " + Nickels + " Nickels " + Pennies + " Pennies");
    }
}

2 个答案:

答案 0 :(得分:0)

对于您计算的每个不同硬币,您需要将其从剩余金额中删除。如(未经测试):

    int Dollars = (int)number;
    int remainingamount = (int)((number-Dollars)*100);
    int Quarters = remainingamount/25;
    remainingamount -= Quaters * 25;
    int Dimes = remainingamount/10;
    remainingamount -= Dimes * 10
    int Nickels = remainingamount/5;
    remainingamount -= Nickels * 5
    int Pennies = remainingamount;

答案 1 :(得分:0)

既然您正在使用Java,那么您是否尝试过JSR 354? 请参阅JavaMoney.orgJSR 354 Detail page at JCP.org它为IMF或欧洲中央银行转换货币单位和默认汇率提供商提供标准API。