gpt4 book ai didi

java - Java 类 BigDecimal

转载 作者:行者123 更新时间:2023-11-30 04:53:52 25 4
gpt4 key购买 nike

我正在尝试使用 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();



}


}

}

最佳答案

您的问题与此相关

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

变量 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);

附注您需要删除 main 方法开头的 Interest 声明。

关于java - Java 类 BigDecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9188887/

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