JAVA换钱

时间:2016-04-01 12:17:28

标签: java if-statement output

我正在尝试编写一个输出货币变化的代码:

**$7.00 remains to be paid. Enter coin or note: $100.00

  You gave $100.00

Your change:

1 x $50.00

2 x $20.00

0 x $10.00

0 x $5.00

1 x $2.00

1 x $1.00

  **

但输出应该相同但没有显示0值,例如它应该是这样的:

**$7.00 remains to be paid. Enter coin or note: $100.00

  You gave $100.00

Your change:

1 x $50.00

2 x $20.00

1 x $2.00

1 x $1.00
  **

我的货币兑换代码看起来像这样,使用if语句:

  double fiftyDollars, twentyDollars, tenDollars, fiveDollars, twoDollars, oneDollar, fiftyCents, twentyCents, tenCents, fiveCents;

        fiftyDollars = change / 50.00; //dividing change by
        change = change % 50.00; //get remainder of the change
                if(fiftyDollars > 0) {
                    System.out.println((int) fiftyDollars + " x $50.00"); //getting output as integer- casting
                }

                twentyDollars = change / 20.00;
        change = change % 20.00;
                if (twentyDollars > 0){
                    System.out.println((int) twentyDollars + " x $20.00");
                }

        tenDollars = change / 10.00;
        change = change % 10.00;
                if (tenDollars >0) {
                    System.out.println((int) tenDollars + " x $10.00");
                }

        fiveDollars = change / 5.00;
        change = change % 5.00;
                if(fiveDollars > 0) {
                    System.out.println((int) fiveDollars + " x $5.00");
                }

        twoDollars = change / 2.00;
        change = change % 2.00;
                if (twoDollars >0) {
                    System.out.println((int) twoDollars + " x $2.00");
                }

        oneDollar = change / 1.00;
        change = change % 1.00;
                if(oneDollar >0) {
                    System.out.println((int) oneDollar + " x $1.00");
                }

        fiftyCents = change / 0.5;
        change = change % 0.5;
                if (fiftyCents >0) {
                    System.out.println((int) fiftyCents + " x $0.50");
                }

        twentyCents = change / 0.2;
        change = change % 0.2;
                if(twentyCents > 0) {
                    System.out.println((int) twentyCents + " x $0.20");
                }

        tenCents = change / 0.1;
        change = change % 0.1;
                if (tenCents > 0){
                    System.out.println((int) tenCents + " x $0.10");
                }

        fiveCents = change / 0.05;
        change = change % 0.05;
                if (fiveCents > 0){
                    System.out.println((int) fiveCents + " x $0.05");
                }

我很感激你们的任何帮助! 谢谢你

3 个答案:

答案 0 :(得分:2)

您可以检查等于或高于1的值。

如在另一个答案中所述,您正在处理double值,因此>0将匹配0.10.56等。

所以:

if (tenDollars >= 1)

答案 1 :(得分:1)

您正在使用双打,因此0值介于0和1之间, 如果你在if子句中将double转换为int,你的程序应该可以正常工作。

答案 2 :(得分:1)

更改所有if条件

if(fiftyDollars > 0) {

if((int)fiftyDollars > 0) {