我想知道为什么会出现错误以及如何为我的java项目修复它。
我必须完全相同:
这就是我在Eclipse上所做的;
double annIntRat;
int nOY;
int borrowMor;
int M;
double monthPay;
double mIR;
Scanner scnr = new Scanner(System.in);
// Your code should go below this line
System.out.print("What is your annual interest rate as a decimal? (ex 0.045): ");
annIntRat = scnr.nextDouble();
System.out.print("How many years will your mortgage be held? ");
nOY = scnr.nextInt();
System.out.print("What amount of the mortgage did you borrow? ");
borrowMor = scnr.nextInt();
DecimalFormat df = new DecimalFormat("0.0");
System.out.println("\nThe number "+annIntRat+" can be represented as "+df.format((annIntRat)*100)+"%");
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
M=defaultFormat.format(borrowMor); //< Here is the error and tells me to change to String.But if I do so, there will be an error down there for monthPay=.....
System.out.println("The mortgage amount is "+M);
mIR=(annIntRat)/12;
monthPay=(mIR * M)/(1-(1/Math.pow(1+mIR,12*nOY)));
答案 0 :(得分:0)
我花了一段时间才看到您突出显示错误的位置,我建议您更明确地了解错误的位置。
您正在使用的NumberFormat的'format'方法返回一种String类型,它可以解释您的错误。
以下应该可以解决问题,尽管您无法确定用户是否输入整数...请记住这一点。
M = Integer.parseInt(defaultFormat.format(borrowMor));
答案 1 :(得分:0)
DecimalFormat.format(long)
方法是NumberFormat
类的继承方法 - NumberFormat.format(long)
。该方法返回String
。
因此,只需使用String
类型的实例来存储和使用方法的返回值:
String borrowMorString = defaultFormat.format(borrowMor);
System.out.println("The mortgage amount is " + borrowMorString);
// …
monthPay = (mIR * borrowMor) / (1 - (1 / Math.pow(1 + mIR, 12 * nOY)));