1

我在尝试编写一个计算贷款利息并以某些小数位显示信息的程序时遇到错误。我需要将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)
4

1 回答 1

1

只是改变

float loanInterest = sc.nextFloat();

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

并且您将解决“float cannot be derefenced”,因为 float 是原始类型并且没有 method setScale

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

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

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

于 2013-01-20T00:05:43.980 回答