Float无法取消引用 - 使用BigDecimal

时间:2013-01-19 23:49:38

标签: java floating-point bigdecimal dereference

我在尝试编写计算贷款利息的程序时出错,并以某些小数位显示信息。我需要loanInterest以3.546%显示,或者类似于3位小数的东西。我能够让totalInterest正确显示,但我不知道这是因为它是我刚刚建立的新值。当我尝试运行我的程序时,如下所示,我得到一个“浮动无法解除引用”的错误。

public class SarahShelmidineModule2Project {

public static void main(String[] args) {
    //Being programing for Module 2 project

    // Welcome the user to the program
    System.out.println("Welcome to the Interest Calculator");
    System.out.println();  // print a blank line

    // create a Scanner object named sc
    Scanner sc = new Scanner(System.in);

    // perform interest calculations until choice isn't equal to "y" or "Y"
    String choice = "y";
    while (choice.equalsIgnoreCase("y"))
    {
        // get info from user on loan amount and interest rates and store data
        System.out.print("Enter loan amount:   ");
        double loanAmount = sc.nextDouble();
        System.out.print("Enter interest rate:   ");
        float loanInterest = sc.nextFloat();


        // calculate the interest and convert to BigDecimal and rounding for totalInterest

       BigDecimal decimalloanAmount = new BigDecimal (Double.toString(loanAmount));
       BigDecimal decimalloanInterest = new BigDecimal (Double.toString(loanInterest));
       BigDecimal totalInterest = decimalloanAmount.multiply(decimalloanInterest);
       totalInterest = totalInterest.setScale(2, RoundingMode.HALF_UP);

       loanInterest = loanInterest.setScale(3, RoundingMode.HALF_UP);

        System.out.println();  // print a blank line

        // display the loan amount, loan interest rate, and interest
        // also format results to percent and currency
        NumberFormat currency = NumberFormat.getCurrencyInstance();
        NumberFormat percent = NumberFormat.getPercentInstance();

        String message =    "Loan amount: " + currency.format(loanAmount) + "\n"
                +           "Interest rate:  " + percent.format(loanInterest) + "\n"
                +           "Intrest:    " + currency.format(totalInterest) + "\n";
        System.out.println(message);

        // inquire if user would like to continue with application
        System.out.print("Continue? (y/n): ");
        choice = sc.next();
        System.out.println();

以下是我运行时遇到的错误:

欢迎使用兴趣计算器

输入贷款金额:10932

输入利率:.0934

Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - Erroneous sym type: <any>     at
 sarahshelmidinemodule2project.SarahShelmidineModule2Project.main(SarahShelmidineModule2Project.java:45)

1 个答案:

答案 0 :(得分:1)

只需更改

float loanInterest = sc.nextFloat();

BigDecimal loanInterest = new BigDecimal(sc.nextFloat());

你将解决&#34;浮动无法解除&#34;因为float是基本类型,并且没有方法setScale

关于打印正确的小数位数,请使用以下内容:

    String currencySymbol = Currency.getInstance(Locale.getDefault()).getSymbol();
    System.out.printf("%s%8.5f\n", currencySymbol, totalInterest);

此代码将使用5位小数,但请确保您的BigDecimal标度至少为5,否则您将获得不重要的零。