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;
}
答案 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();