我的循环错了。全新的Java。关于我哪里出错的任何见解?我应该计算硬币

时间:2015-10-10 20:04:18

标签: java

我正在开发一个计算用于产生一定总变化的硬币数量的项目。出于某种原因,我的输出只是读这个: 宿舍: 助攻: 结束。

它不打印正在计算的整数,也不会继续超过硬币。我尝试过使用不同的循环和打印语句,但我不知所措。任何有关提示的见解都将非常感激。

Long

}

3 个答案:

答案 0 :(得分:2)

首先是循环:

change = quarters - 25;

应该是

change = change - 25;

然后三个if循环也应该是while循环。

答案 1 :(得分:1)

更改:

System.out.printf("Quarters:\n", quarters);

对此:

System.out.printf("Quarters:%d\n", quarters);

为硬币,镍币,便士做同样的事情。 我进一步观察并发现了一些代码问题。 这应该让它工作:

while (change >= 25) {
            quarters = quarters + 1;
            change = change - 25;
        }
        if (quarters > 0) {
            System.out.printf("Quarters:%d\n", quarters);
        }

        if (change >= 10) {

            dimes = dimes + 1;
            change = change - 10;
            System.out.printf("Dimes:%d\n", dimes);

        }
        if (change >= 5) {

            nickels = nickels + 1;
            change = change - 5;
            System.out.printf("Nickles:%d\n", nickels);

        }
        if (change > 0) {
            System.out.printf("Pennies:%d\n", change);
        }

答案 2 :(得分:1)

我认为这应该有效:

    int change = 0;
    int quarters = 0;
    int dimes = 0;
    int nickels = 0;

    Scanner in;
    in = new Scanner(System.in);
    System.out.println("Lets calclulate the minimum coins.\n");
    System.out.println("PLease enter amount of change.(1-99)\n");
    change=in.nextInt(); //asks for the amount of change to calculate


    //start of while loop
    while  ( change >= 25)
    {
        quarters = quarters+1;
        change = change - 25;

    } 
    System.out.printf("Quarters:\n"+quarters+"\n");
    while (change>=10)
    {

        dimes = dimes + 1;
        change = change - 10;


    }
    System.out.printf("Dimes: \n"+dimes+"\n");
    while(change>=5)
    {

        nickels = nickels + 1;            
        change = change - 5;


    }
    System.out.printf("Nickles: \n"+nickels+"\n");
    if ( change>0)
        System.out.printf("Pennies: \n"+change+"\n");