所以,我制定了一个程序,在给定价格(加5%税)和用户付款时计算变更。我需要这个代码的其余要求是:
0
或任何负数(即-2
)。完整输出,所有可能的用户选择应如下所示:
Cost of transaction (enter 0 or negative to exit; max is $500.00): 1000
Cost of transaction (enter 0 or negative to exit; max is $500.00): 501
Cost of transaction (enter 0 or negative to exit; max is $500.00): 500
Amount due (with 5.00% tax): $525.00
Please enter payment amount: 1000.57
Change back $475.57
$100: 4 $50: 1 $20: 1 $10: 0 $5: 1 $1: 0 $0.25: 2 $0.10: 0 $0.05: 1
$0.01: 2
Cost of transaction (enter 0 or negative to exit; max is $500.00): 0
Done.
这是我的代码:
/*
* @author (Zach Daly)
* <p> (MakeChange.java)
* <p> (Project2)
* <p> (Make change)
*/
import java.util.*;
public class MakeChange
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
double price;
double amountPaid;
int paidInt;
int priceWithTaxInt;
double priceWithTaxDbl;
final double TAX_RATE = .05;
int change;
int hundreds, fifties, twenties, tens, fives, ones, quarters, dimes, nickels, pennies;
System.out.print("Cost of transaction (enter 0 or negative to exit; max is $500.00): ");
price = in.nextDouble();
priceWithTaxDbl = price + (price * TAX_RATE);
System.out.printf("Amount due (with 5.00%% tax): $%3.2f\n", priceWithTaxDbl);
System.out.println("Please enter payment amount: ");
amountPaid = in.nextDouble();
paidInt = (int) (amountPaid * 100);
priceWithTaxInt = (int) (priceWithTaxDbl * 100);
if (price <= 0)
{
System.out.println("Done.");
}
change = paidInt - priceWithTaxInt;
double changePrint = (double) change / 100;
System.out.println(changePrint);
if (change == 0)
{
System.out.println("Exact change! Amazing!");
}
if (paidInt > priceWithTaxInt)
{
hundreds = change / 10000;
if (hundreds > 0)
{
change %= 10000;
}
fifties = change / 5000;
if (fifties > 0)
{
change %= 5000;
}
twenties = change / 2000;
if (twenties > 0)
{
change %= 2000;
}
tens = change / 1000;
if (tens > 0)
{
change %= 1000;
}
fives = change / 500;
if (fives > 0)
{
change %= 500;
}
ones = change / 100;
if (ones > 0)
{
change %= 100;
}
quarters = change / 25;
if (quarters > 0)
{
change %= 25;
}
dimes = change / 10;
if (dimes > 0)
{
change %= 10;
}
nickels = change / 5;
if (nickels > 0)
{
change %= 5;
}
pennies = change;
System.out.printf(
"Change back $%.2f\n$100: %d $50: %d $20: %d $10: %d $5: %d $1: %d $0.25: %d $0.10: %d $0.05: %d $0.01: %d\n",
changePrint, hundreds, fifties, twenties, tens, fives, ones, quarters, dimes, nickels, pennies);
}
in.close();
}
}
答案 0 :(得分:0)
我相信你要找的是一个do-while循环。它将运行一次,并一直重复,直到不满足while条件:
do {
System.out.print("Cost of transaction (enter 0 or negative to exit; max is $500.00): ");
price = in.nextDouble();
//repeating logic
if (price > 500) {
price = 0;
System.out.println("Maximum price was exceeded");
}
} while (price >= 0);