程序退出之前它意味着完成

时间:2015-03-23 00:04:05

标签: java while-loop

所以我制作一个评估程序充当自动售货机,询问你想要购买多少罐,然后计算价值,要求输入硬币(假设用户是明智的),然后尝试计算给出的改变。

我遇到的问题是,在程序读入付款的价值并计算出是否足够以下内容之后:

double coins[] = new double[]{2.00,1.00,0.50,0.20,0.10,0.05};

//A while loop so that it continues to go until the payment is equal or more than the cost
int count2 = 1;
while (payment <= totalCost){

  if (payment == totalCost){
    System.out.println("You have entered the exact amount of change! Thankyou.");
    break;
  }

  System.out.println("Please enter more coins: ");

  coinsIn[count2] = kbd.nextDouble();
  payment = payment + coinsIn[count2];

  count2++;
}

它刚刚结束该计划。

问题是,在那之后直接循环我有这个代码示例

double change = payment - totalCost;
int count3 = 0;
if ((change == coins[count3]) && (count3 <6)) {
  System.out.println("Your change is: ");
  System.out.println(change);
}
else{
  count3++;
}

应该运行,但事实并非如此。

例如说总成本为4.50美元,我输入2 x 2.00和1x 1.00它应该贯穿if if循环并发现在硬币[]中有硬币的.50值[2],然后打印更改的消息然后退出。

这是终端中的工作示例:

   Please enter the amount of cans that you would like to purchase:
1
Please enter the amount of cans that you would like to purchase:
1
Please enter the amount of cans that you would like to purchase:
1
There are currently [297] cans remaining.
The total cost of your purchase is [$4.5].
Please enter your payment now:
2.00
Please enter more coins:
2.00
Please enter more coins:
1.00

它刚好在1.00之后结束,

我不明白这里发生了什么。

非常感谢任何帮助。

P.S。一切都很好。

1 个答案:

答案 0 :(得分:0)

尝试更改count3变量的初始化。你确定使用count3 ??