谁能告诉我我在做什么错。我需要从用户输入到一些JOptionPane-input-dialog-boxes中计算一些值,然后输出答案。

我将不胜感激。提前致谢!


输入项

要比较的贷款数量(可以大于1)
售价
首付
您将针对他们想要比较的每笔贷款询问以下内容

利率
年数


处理中

对于给定的利率和年数,您将需要计算d部分中列出的每种情况的每月付款。

输出量

售价
首付
贷款额度
每个方案清单

利益
年份
付款




到目前为止,这是我的代码:

    package javamortgagecalculator;
    import javax.swing.JOptionPane;
    import java.util.*;
    public class JavaMortgageCalculator {
         public static void main(String[] args) {
              //A. Enter the Number Of Loans to compare
              String numberOfLoansString = JOptionPane.showInputDialog("Enter the Number Of Loans to Compare");
              //Convert numberOfLoansString to int
              int numberOfLoans = Integer.parseInt(numberOfLoansString);

              //B. Enter the Selling Price of Home
              String sellingPriceString = JOptionPane.showInputDialog("Enter the Loan Amount");
              //Convert homeCostString to double
              double sellingPrice = Double.parseDouble(sellingPriceString);

              //C. Enter the Down Payment on the Home
              String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home");
              double downPayment = Double.parseDouble(downPaymentString);

              //Get the loanAmount by Subtracting the Down Payment from homeCost
              double loanAmount = sellingPrice - downPayment;

              //D. Ask the following for as many number of loans they wish to compare
              //D1 Get the interest rate
              double[] annualInterestRatesArray = new double[numberOfLoans];
              double[] monthlyInterestRateArray = new double[numberOfLoans];
              int[] numberOfYearsArray = new int[numberOfLoans];
              double[] monthlyPaymentArray = new double[numberOfLoans];
              double[] totalPaymentArray = new double[numberOfLoans];
              int counter = 1;

              for (int i=0; i < numberOfLoans; i++)
              {
                  String annualInterestRateString = JOptionPane.showInputDialog("Enter           the interest rate for Scenario " + counter);
                  double annualInterestRate = Double.parseDouble(annualInterestRateString);
                  annualInterestRatesArray[i] = (annualInterestRate);

                  //Obtain monthly interest rate
                  double monthlyInterestRate = annualInterestRate / 1200;
                  monthlyInterestRateArray[i] = (monthlyInterestRate);

                  //D2 Get the number of years
                  String numberOfYearsString = JOptionPane.showInputDialog("Enter the      number of years for Scenario " + counter);
                  int numberOfYears = Integer.parseInt(numberOfYearsString);
                  numberOfYearsArray[i] = (numberOfYears);

                  //Calculate monthly payment
                  double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
                  //Format to keep monthlyPayment two digits after the decimal point
                  monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
                  //Store monthlyPayment values in an array
                  monthlyPaymentArray[i] = (monthlyPayment);

                  //Calculate total Payment
                  double totalPayment = monthlyPaymentArray[i] * numberOfYears * 12;
                  //Format to keep totalPayment two digits after the decimal point
                  totalPayment = (int)(totalPayment * 100) / 100.0;
                  totalPaymentArray[i] = (totalPayment);

                  counter++;
              }

              StringBuilder sb = new StringBuilder();
              for (int i = 0; i < numberOfLoans; i++) {
                     sb.append(String.format("\t \t \t \t \t \n", sellingPrice, downPayment, loanAmount, Arrays.toString(annualInterestRatesArray),           Arrays.toString(numberOfYearsArray), Arrays.toString(monthlyPaymentArray)));
              }
              String toDisplay=sb.toString();

              JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
          }
     }

最佳答案

如果我可能是被伪装成程序设计老师的绿色巨人(尤其是丑陋的巨魔)强迫使用多个JOption窗格进行输入和输出,那么这就是我要解决的问题。这仅是为您提供信息...如果您将其作为自己的工作上交,老师会闻到老鼠的气味,巨魔也有Google。

package forums;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;

/**
 * Compares total cost of mortgages (aka ordinary annuity certains)
 */
public class MortgageCalculator
{
  public static void main(String[] args)
  {
    // 1. input
    final double price = Enter.aDouble("the purchase of the property");
    final double deposit = Enter.aDouble("down payment");
    Loan.setPrinciple(price - deposit);

    int numLoans = Enter.anInteger("number of loans to compare");
    Loan[] loans = new Loan[numLoans];
    for ( int i=0; i<numLoans; ++i ) {
      loans[i] = new Loan(
          Enter.aDouble("Annual interest rate for Loan " + (i+1) + "  (eg: 6.75)") / 100.0 / 12.0
        , Enter.anInteger("number of years for Loan " + (i+1) + "  (eg 20)") * 12
      );
    }

    // 3. Output
    final String caption =
        "Principle " + Format.money(Loan.getPrinciple())
      + " = Price " + Format.money(price)
      + " - Deposit " + Format.money(deposit);

    StringBuilder results = new StringBuilder(64 + numLoans * 64);
    results.append("Monthly Rate, Months, Monthly Repayment, Total Repayments\n");
    for ( Loan l : loans ) {
      results.append(String.format("%5s, %d, %13s, %13s\n"
        , Format.percent(l.rate)
        , l.periods
        , Format.money(l.payment())
        , Format.money(l.totalPayment())
      ));
    }
    JOptionPane.showMessageDialog(null, results.toString(), caption, JOptionPane.INFORMATION_MESSAGE);
  }

  static class Format
  {
    static java.text.Format MONEY = new DecimalFormat("$#,###.##");
    static String money(double amount) {
      return MONEY.format(amount);
    }

    static java.text.Format PERCENT = new DecimalFormat("0.###%");
    static String percent(double amount) {
      return PERCENT.format(amount);
    }

    static StringBuilder join(String between, Object... values) {
      StringBuilder result = new StringBuilder(values.length * 16);
      if ( values.length > 0 ) {
        result.append(values[0].toString());
        for ( int i=1; i<values.length; ++i ) {
          result.append(between)
            .append(values[i].toString());
        }
      }
      return result;
    }

  } // end class Format

  static class Enter
  {
    public static int anInteger(String fieldDesc) {
      return Integer.parseInt(JOptionPane.showInputDialog("Enter the "+ fieldDesc));
    }

    public static double aDouble(String fieldDesc) {
      return Double.parseDouble(JOptionPane.showInputDialog("Enter the "+ fieldDesc));
    }
  } // end class Enter

} // end class MortgageCalculator

class Loan
{
  private static double principle = 34324.121221312432;
  final double rate;
  final int periods;

  static void setPrinciple(double principle) {
    if (Loan.principle != 34324.121221312432)
      throw new ReadOnlyException("The Principle can't be changed once set.");
    Loan.principle = principle;
  }

  static double getPrinciple() {
    return Loan.principle;
  }

  /**
   * Initialises a new loan objects
   * @param double rate The interest rate per period, as a percentage.
   *  eg: 0.00625 is 7.5% per annum.
   * @param int periods The number of periods of the loan, typically months.
   */
  Loan(double rate, int periods) {
    this.rate = rate;
    this.periods = periods;
  }

  // 2. processing
  double payment() {
    return principle * rate / (1 - 1/Math.pow(1+rate,periods) );
  }

  double totalPayment() {
    return periods * payment();
  }

}

class ReadOnlyException extends RuntimeException
{
  private static final long serialVersionUID = 0L;
  public ReadOnlyException(String message) {
    super(message);
  }
}


“要比较的贷款清单”由Loan对象的数组表示...即:每个“贷款选项”由Loan类的实例表示,该实例将特定贷款的所有属性分组为一个很好的整洁的“事物”,我们可以整体上对其进行操作。比您用来存储借贷属性的技术(称为“并行数组”)更好的方法是……嗯,嗯,这有点过时了,实际上它有(油腻的)鱼,戴着(太紧)橙色的野生动物园套装,头带(番红花粉红色的)……在八十年代看起来并不好看,如今,很可能会让您遭到殴打,逮捕或两者兼而有之;取决于您的语言环境...基本上:我们现在有更好的方法!

Loan类还具有几个方便的“计算字段”来为我们进行计算。这意味着,如果将来我们计算还款方式时由于某种原因而发生变化,我们只有一个地方可以更改它,并且所有使用贷款的内容(可能是读取,写入,置换,总计,收回或什至批发贷款)都可以不必更改...他们只是免费获取更改。

在这种人为设计的用例中,我们所有的贷款都将具有相同的金额,只有利率和期限有所不同...因此,Loan类还具有一个名为“ principle”的static变量,该变量具有“ common”贷款类的所有实例的基本原则。原则只能设置一次。任何随后的设置原理的尝试都将引发ReadOnlyException。

无论如何,我希望您能从另一种解决自己练习中发现的子问题的方法中学到一些东西。未来的秘诀:抓住同学的代码进行练习,并通读它……您可以从其他人的应对方式中学到很多东西。

干杯。基思

10-06 13:57