我正在嘗試使用BigDecimal類爲學校編寫一個程序。該計劃是利率計算器和最終的輸出應該像somethig:BigDecimal Class Java
Loan Amount: whatever loan amount is in dollars
Interest Rate: as a percent
Interest: amount of interest paid in dollars
continue? Y/N:
這本書不是關於如何編寫BigDecimal類清楚,我使用Eclipse,因此任何時候,我做出改變我收到一個令人困惑的錯誤。 有人可以看看這個,並讓我在正確的方向嗎?我正在使用Murach的Java SE6,這本書不是很有幫助。
謝謝!
import java.util.Scanner; //import scanner
import java.text.NumberFormat; //import number format
import java.math.*; //import math classes
public class InterestCalculator //create public class
{
public static void main(String[] args)
{
Scanner calc = new Scanner(System.in); //create scanner
double LoanAmount, InterestRate, Interest; //declareLoanAmount,InterestRate, and Interest as double
//welcome user to the Interest Rate Calculator
System.out.println("Welcome to The Interest Rate Calculator");
System.out.println();
//perform choice calculations until choice isn't equal to "y" or "Y"
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
//Get Loan Amount from user
System.out.println("Enter Loan Amount: ");
LoanAmount = calc.nextDouble();
//Get Interest rate from user
System.out.println("Enter Interest Rate: ");
InterestRate = calc.nextDouble();
BigDecimal decimalInterest = new BigDecimal(Double.toString(Interest));
decimalInterest = decimalInterest.setScale(2, RoundingMode.HALF_UP);
BigDecimal decimalInterestRate = new BigDecimal(Double.toString(InterestRate));
decimalInterestRate = decimalInterestRate.setScale(2, RoundingMode.HALF_UP);
//calculate interest
System.out.println("message");
//prompt user to continue?
System.out.println("Continue? Y/N: ");
choice = calc.next();
System.out.println();
}
}
}
我還遇到了編碼計算問題,應該是類似Interest = LoanAmount * InterestRate的計算,我知道我底部的打印只會打印單詞「消息」。在我之前的嘗試中,我試圖編寫一個字符串來打印我的整個輸出,並標題爲字符串消息。 – 2012-02-08 06:47:18
你會得到什麼錯誤? – Kris 2012-02-08 06:48:19
我建議你看看[BigDecimal javadoc](http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html) - 它非常全面。一般來說,'BigDecimal'是不可變的,所以每次執行操作時都會得到一個新實例。像這樣:'BigDecimal someValue = decimalInterest.multiply(decimalInterestRate);'除此之外,你不需要字符串轉換像'Double.toString(Interest)' - 'BigDecimal' ctor接受雙打和什麼不看(看看javadoc!) – 2012-02-08 06:49:43