不能使用BigDecimal对Float进行解引用



我得到一个错误试图编码一个程序,计算贷款利息,并显示信息与某些小数点后的位置。我需要loanInterest显示为3.546%,或者类似的,小数点后3位。我能够让totalInterest正确显示,但我不知道这是因为它是我刚刚建立的新值。当我试着像下面这样运行我的程序时,我得到了一个"float不能被解引用"的错误。

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)

直接修改

float loanInterest = sc.nextFloat();

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

,你将解决"float不能被捍卫",因为float是一个基本类型,没有setScale方法。

关于打印正确的小数数,使用如下命令:

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

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

相关内容

  • 没有找到相关文章

最新更新