[英]DecimalFormat.format method call: incompatible types
I wanted to know why there is an error and how to fix it for my java project.我想知道为什么会出现错误以及如何为我的 Java 项目修复它。
I have to make exactly same out as these:我必须做出与这些完全相同的事情:
And this is what I did on Eclipse;这就是我在 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)));
It took me a while to see where you highlighted your error, I would recommend being more explicit with where your errors are.我花了一段时间才看到您突出显示错误的位置,我建议您更明确地说明错误的位置。
The 'format' method of NumberFormat you are using returns a type of String, which would explain your error.您正在使用的 NumberFormat 的 'format' 方法返回一种字符串类型,这可以解释您的错误。
The following should do the trick, although you can't be certain that a user is to input an integer...take that in mind.以下应该可以解决问题,尽管您不能确定用户是否要输入整数……请记住这一点。
M = Integer.parseInt(defaultFormat.format(borrowMor));
The DecimalFormat.format(long)
method is an inherited method from the NumberFormat
class — NumberFormat.format(long)
. DecimalFormat.format(long)
方法是从NumberFormat
类 - NumberFormat.format(long)
继承的方法。 The method returns an instance of String
.该方法返回
String
一个实例。
So, just use an instance of the String
type to store and use the return value of the method:因此,只需使用
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)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.