Java程序没有正确累积

时间:2014-03-23 21:29:08

标签: java

因此,当我运行此代码时,它只会在每个变量上放置1然后结束。它没有正确累积我的总硬币。它似乎不是我的while循环实际上没有循环,它只是添加一个总数然后转到下一个循环。我对发生的事情感到困惑,所以对任何帮助表示赞赏!

以下链接指向运行后的内容:http://imgur.com/p3hsBrC

package MinumumCoins;

public class MinimumCoins
{

  public static void main(String[] args)
  {
  System.out.println("Please enter amount of change (1-99)");
  System.out.println("");

 Keyboard kbd;
 kbd= new Keyboard();

 int totQuarters = 0;
 int totDimes = 0;
 int totNickles = 0;
 int totPennies = 0;
 int Amount = kbd.readInt();



   while (Amount>=25)

       Amount=Amount-25;

           totQuarters=totQuarters+1;



   while (Amount>=10)

       Amount=Amount-10;

               totDimes=totDimes+1;



    while (Amount>=5)

        Amount=Amount-5;

                totNickles=totNickles+1;



    while (Amount>=1)

        Amount=Amount-1;

            totPennies=totPennies+1;

   System.out.println("");
   System.out.println("Quarters: "+totQuarters);
   System.out.println("Dimes: "+totDimes);
   System.out.println("Nickles: "+totNickles);
   System.out.println("Pennies: "+totPennies);





  } //end of main string

} //end of class

2 个答案:

答案 0 :(得分:2)

您需要用括号{}将语句括在块中,否则只会在循环中执行第一行:

此:

 while (Amount>=25) 
           Amount=Amount-25;    
           totQuarters=totQuarters+1;

将执行为:

while (Amount>=25)    
   Amount=Amount-25;       // this is in the loop.
totQuarters=totQuarters+1; // this is not in the loop.

请改为:

while (Amount>=25) {    
       Amount=Amount-25;    
       totQuarters=totQuarters+1;
}

为所有while循环更改此内容。

此外,如果您想节省空间,可以使用复合赋值运算符amount = amount - 25重写为amount -= 25,并在表格totQuarters=totQuarters+1上重写1}}可以使用后缀增量运算符编写为totQuarters++,或使用前缀增量运算符编写为++totQuarters

答案 1 :(得分:0)

将{}添加到循环中。否则它只运行一次,因为它只运行第一行。

实施例

while (Amount>=25) {
   Amount=Amount-25;
   totQuarters=totQuarters+1;
}

while (Amount>=10) {
   Amount=Amount-10;
   totDimes=totDimes+1;
}

while (Amount>=5) {
   Amount=Amount-5;
   totNickles=totNickles+1;
}

while (Amount>=1) {
    Amount=Amount-1;
    totPennies=totPennies+1;
}