Java 计划在本应终止之前退出

Java 计划在本应终止之前退出,java,while-loop,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

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

我遇到的问题是,在程序读入付款值并计算是否足够后,请执行以下操作:

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++;
}
1点之后就结束了

我不明白这里发生了什么

任何帮助都将不胜感激


顺便说一句,一切都很好

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

请考虑提供一个演示您的问题的示例。这不是一个代码转储,而是您正在做的一个示例,它突出了您所遇到的问题。这将减少混乱和更好的响应在调试器下运行代码,您可以看到逐步的进度并检查变量。看起来一个问题是count3没有正确递增。最后的增量必须在while循环中才能影响前面的条件。此外,对于一个名为“coins”的数组没有声明,因此很难看到您正在尝试执行的操作。
change=totalCost-payment在循环后将为非正。这是故意的吗?这是个简单的错误,谢谢@fabian
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++;
}
   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