gpt4 book ai didi

java - Float 无法取消引用 - 使用 BigDecimal

转载 作者:太空宇宙 更新时间:2023-11-04 07:51:21 33 4
gpt4 key购买 nike

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

最佳答案

改变一下

float 贷款利息 = sc.nextFloat();

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

并且您将解决“float 无法取消引用”的问题,因为 float 是原始类型并且没有方法 setScale

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

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

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

关于java - Float 无法取消引用 - 使用 BigDecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14420182/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com