BigDecimal类Java

时间:2012-02-08 06:46:05

标签: java

我正在尝试使用BigDecimal类为学校编写程序。该程序是一个利率计算器,最终输出应该是如下:

    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();



                }


        }

    }

1 个答案:

答案 0 :(得分:2)

您的问题与此相关

BigDecimal decimalInterest = new BigDecimal(Double.toString(Interest));

此时变量利息不会被初始化。

这样的事情应该可以完成这项工作(但是我没有改进你的编码风格):

        BigDecimal decimalInterestRate = new BigDecimal(Double.toString(InterestRate));
        decimalInterestRate = decimalInterestRate.setScale(2, RoundingMode.HALF_UP);
        BigDecimal decimalLoanAmount = new BigDecimal(Double.toString(LoanAmount));
        decimalLoanAmount = decimalLoanAmount.setScale(2, RoundingMode.HALF_UP);

        // calculate interest
        BigDecimal Interest = decimalInterestRate.multiply(decimalLoanAmount);

        System.out.println("Interest:" + Interest);

P.S。您需要在main方法的最开头删除Interest声明。