试图让我的while循环使用适合条件的值,而不是使用给定Java的第一个输入

时间:2019-02-28 04:37:27

标签: java loops while-loop

所以我试图弄清楚为什么while循环采用给定的第一个值,即使它不符合标准(大于250)也将其用于我的方程式

Scanner kb = new Scanner(System.in);

double cost;
double costWithTax;
double costWithSurcharge;
double payment;
double changeDue;
double costWithTaxAndSurcharge;

//equations
costWithTax = (cost * taxRate) + cost;
surcharge = cost * surcharge;
costWithTaxAndSurcharge = costWithTax + surcharge;

if (cost < 10)
{
        cost = surcharge + costWithTax;
    System.out.printf("Amount due: $%.2f ", cost);
    System.out.println("");
    System.out.printf("Surcharge added is: $%.2f ", surcharge);
}
else if (cost <= 250)
{
    cost = costWithTax;
    System.out.printf("Amount due: $%.2f ", cost);
}
while (cost > 250)
{
    System.out.print("Enter transaction amount: ");
    cost = kb.nextDouble();
    cost++;

        cost  = costWithTax;
    System.out.printf("Amount due: $%.2f ", cost);
    break;  
}

1 个答案:

答案 0 :(得分:0)

您的过程很混乱。我已经修改了代码并添加了注释。请参阅下面的代码。

Scanner kb = new Scanner(System.in);

double cost;
double costWithTax;
double costWithSurcharge;
double payment = 0; // initialized payment
double changeDue;
double costWithTaxAndSurcharge;
double taxRate = 0.07; // 7% tax
double surcharge = 0.10; // 10% surcharge

System.out.print("Enter transaction amount: "); // get the cost first before doing the equations
cost = kb.nextDouble();

while (cost > 250) { // check if the cost is greater than 250, since if greater than 250 it is an invalid cost (from your explanation)
    System.out.print("Input greater than $250. Pleas enter transaction amount again: ");
    cost = kb.nextDouble(); // get the cost again
}

// equations
costWithTax = (cost * taxRate) + cost; // get the cost with the tax added to it
costWithSurcharge = cost * surcharge; // change to costWithSurcharge from surcharge, so that the value of surcharge will not be overwritten, this will be the cost with surcharge
costWithTaxAndSurcharge = costWithTax + costWithSurcharge; // (#1) get the new cost, cost with tax and surcharge 

if (cost < 10) {
    cost = costWithTaxAndSurcharge; // just assign costWithTaxAndSurcharge to cost, no need to calculate again, same calculations with (#1) above
    System.out.printf("Amount due: $%.2f ", cost);
    System.out.println("");
    System.out.printf("Surcharge added is: $%.2f ", surcharge);
} else if (cost <= 250) {
    cost = costWithTax;
    System.out.printf("Amount due: $%.2f ", cost);
}

System.out.print("Enter payment amount: ");
payment = kb.nextDouble();

while (payment <= cost) {
    System.out.print("Payment is invalid. Enter payment amount agian: ");
    payment = kb.nextDouble();
}

changeDue = payment - cost;
System.out.print("Change due: " + changeDue);

kb.close();