我写了抵押计算器代码,但在调试时遇到了异常

问题描述 投票:0回答:3
import java.text.NumberFormat;

 public class Mortgage {
 public static void main(String[] args) {
    int p = 1000000;
   NumberFormat percent = NumberFormat.getPercentInstance();
   double r = Double.parseDouble(percent.format(3.92*12));

    int t = (int)(r);
    double n;
    n = Math.pow(30,12);
    int f = (int) Math.floor(n);

    int a =(1+t)^f;
    int b = (a-1);
    int c = (t*a)/b;
    int m = p*c;
    NumberFormat currency = NumberFormat.getCurrencyInstance();
    String result = currency.format(m);

    System.out.println(result);

    }
 }

我尝试将r更改为int,但仍然出现异常。我写错了什么?

java number-formatting numberformatexception
3个回答
1
投票

您使用NumberFormat.getPercentInstance()设置号码格式。这将添加一个%符号和其他数字格式(取决于您的默认语言环境)。然后Double.parseDouble(...)调用失败,因为该数字不是纯双数。

不需要格式化和解析数字,您可以直接将其分配给double变量,因为它始终是常量。


1
投票

我看到几个问题。

    double n;
    n = Math.pow(30,12);
    int f = (int) Math.floor(n);

30至12的幂。对于30年的抵押贷款来说,这没有意义。您的意思是30*12个支付期的360。或可能是Math.pow(30,1+montlyRate),其中monthlyRate = (AR/100)/12AR = annual rate)。

    int a =(1+t)^f;

操作员^不是电源,而是exclusive OR。您可能也不想这么做。

我建议您查看有关计算Mortage Payments的Wiki条目>

这里是一种计算方法,然后每月显示一次。

      double in = 11.5; // annual percentage rate
      double mo_rate = (in / 100) / 12.; // monthly rate
      double PV = 92_500.; // present value (cost of the house).
      double f = Math.pow(1 + mo_rate, 360); // factor resulting from the linear
                                             // expansion

      double payment = mo_rate * PV * f / (f - 1); // Monthly payment inclusing
                                                   // interest and
                                                   // principal
      for (int i = 0; i <= 360; i++) {
         double mo_int = PV * mo_rate; // montly interest for loan
         double principal = payment - mo_int;
         System.out.printf(
               "Payment = %5.2f, Mo interest = %5.2f, Principal = %5.2f%n",
               payment, mo_int, payment - mo_int);
         PV -= principal; // future interest is based on loan value less what
                          // you have already paid.
      }

注意:不同的银行和/或国家/地区的做法可能不同。


0
投票

答案是例外java.lang.NumberFormatException: For input string: "4,704%"

© www.soinside.com 2019 - 2024. All rights reserved.