我正在尝试使用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