我對Java很有興趣,我正在嘗試編寫一個程序,給出兩美元輸入的更改量。我無法弄清楚發生了什麼事。我試圖輸出貨幣時遇到了麻煩。例如,如果一個人欠了654.32美元並且支付了987美元,他們的變化應該是332.68美元,這將是2個季度,1個硬幣,1個鎳和3個小兔子。計算所需更改的金額
任何幫助,非常感謝!
import java.util.*;
import java.math.*;
import java.text.*;
public class CorrectChange {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
BigDecimal AmtDue;
BigDecimal AmtPaid;
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US);
//User enters the amount that the customer owes
System.out.println("Enter the amount below that is due to be paid.");
System.out.print("$");
AmtDue = input.nextBigDecimal();
//Converts user's input into the currency format
AmtDue = AmtDue.setScale(2, BigDecimal.ROUND_HALF_UP);
double dAmtDue = AmtDue.doubleValue();
String eAmtDue = n.format(dAmtDue);
//User enters the amount that the customer paid
System.out.println("Enter the amount below that has been paid.");
System.out.print("$");
AmtPaid = input.nextBigDecimal();
//Converts user's input into the currency format
AmtPaid = AmtPaid.setScale(2, BigDecimal.ROUND_HALF_UP);
double dAmtPaid = AmtPaid.doubleValue();
String eAmtPaid = n.format(dAmtPaid);
//Checks to see if the amount paid is more than the amount owed
if (AmtDue.compareTo(AmtPaid)> 0){
double dBal = AmtDue.subtract(AmtPaid).doubleValue();
String eBal = n.format(dBal);
System.out.println("You still owe: " + eBal.toString());
}
//Checks to see if the amount owed is more than the amount paid
if (AmtDue.compareTo(AmtPaid)< 0){
int cBal = (AmtPaid.compareTo(AmtDue)*100);
double dBal = AmtPaid.subtract(AmtDue).doubleValue();
String eBal = n.format(dBal);
int DolBills = (int) (dBal/1);
dBal = dBal % 1;
int quarters = (int) (dBal/25);
dBal = dBal % 25;
int dimes = (int) (cBal/10);
cBal = cBal % 10;
int nickles = (int) (cBal/5);
cBal = cBal % 5;
//pennies = (int) (dBal/100);
//dBal = dBal % 100;
System.out.println("You owe a balance of " + eAmtDue.toString() + ". Since you paid the amount of " + eAmtPaid.toString() + " your change is " + eBal.toString());
System.out.println("Your change amount is as follows:\n" +
"\t" + DolBills + " $1 dollar bills \n" +
"\t" + quarters + " quarters \n" +
"\t" + dimes + " dimes \n" +
"\t" + nickles + " nickels \n");
"\t" + numPennies + " pennies";
}
//Checks to see if the amount paid is equal to the amount owed
if (AmtDue.compareTo(AmtPaid)== 0){
System.out.println("Your balance has been paid. Thank you for your business.");
}
}
使用調試器來了解發生了什麼 – Jens
您向我們展示了您的預期結果,但是當您執行該程序時,您的結果是什麼? –