1

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

我将非常感谢我得到的任何帮助。提前致谢!

  1. 输入
    • 要比较的贷款数量(可能超过 1 个)
    • 售价
    • 首付
    • 对于他们想要比较的每笔贷款,您将询问以下内容
      • 利率
      • 年数
  2. 加工
    • 对于给定的利率和年数,您将需要计算 d 部分中列出的每个方案的每月付款。
  3. 输出
    • 售价
    • 首付
    • 贷款额度
    • 每个场景的列表
      • 兴趣
      • 支付

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

    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);             
          }
     }
4

6 回答 6

2

如果我被迫(大概是被一个伪装成编程老师的大绿色、特别丑陋的巨魔)强迫使用多个 JOption 窗格进行输入和输出,那么这就是我解决问题的方法。这仅供您参考……如果您将其作为自己的工作提交,您的老师会闻到老鼠的味道,而巨魔也有谷歌。

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该类将特定贷款的所有属性分组为一个整洁的“事物”然后我们可以将其作为一个整体进行操作。这比您用来存储贷款属性的技术(称为“并行数组”)更好的方法......嗯,嗯,它有点过时了,事实上它有一个(油腻的)鲻鱼,它穿着(太紧)橙色狩猎服,头带(深红粉色)……在 80 年代看起来并不好看,而现在,它很可能会让你被殴打、被捕或两者兼而有之;取决于您的语言环境...基本上:我们现在有更好的方法!

该类Loan还有几个方便的“计算字段”来为我们进行计算。这意味着,如果将来我们计算还款的方式因某种原因发生变化,我们只有一个地方可以改变它,而使用贷款的一切(可能是读取、写入、置换、总计、收回甚至批发贷款)确实不必改变......他们只是“免费”获得改变。

在这个人为的用例中,我们所有的贷款都将针对相同的金额,只有利率和期限有所不同......所以Loan该类还有一个static名为“原则”的变量,它持有所有实例的“共同”原则贷款班。原则只能设置一次。任何后续设置原则的尝试都将导致抛出 ReadOnlyException。

无论如何,我希望你能从另一种方法中学到一些东西,以解决你在自己做这个练习时可能发现的一些子问题。对未来的一个提示:为这个练习获取你的同学的代码并通读它......你可以从其他人如何处理事情中学到很多东西。

干杯。基思。

于 2011-06-11T07:03:00.797 回答
1
for (int i = 0; i < numberOfLoans; i++)
{
    sb.append(/*...snip...*/ Arrays.toString(annualInterestRatesArray), Arrays.toString(numberOfYearsArray), Arrays.toString(monthlyPaymentArray));
}

你还没有告诉我们问题是什么,但我认为这不是你想要的。每次循环进行时,您都要求程序打印出整个三个数组。相反,您可能想要访问每笔贷款的特定数组元素,对吧?就像是...

for (int i = 0; i < numberOfLoans; i++)
{
    sb.append(/*...snip...*/ annualInterestRatesArray[i], numberOfYearsArray[i], monthlyPaymentArray[i]);
}
于 2011-06-11T03:30:10.203 回答
1
String.format("\t \t \t \t \t \n", sellingPrice, ...

那只会输出5个标签。你要

String.format("%s %s %s %s %s %n", sellingPrice, ...
于 2011-06-11T03:12:39.687 回答
1

现在您需要检查result返回的 by showMessageDialog(),如下所示

于 2011-06-11T02:04:27.183 回答
1

JOptionPane.showMessageDialog(null...在一个 for 循环中。所以它将显示它的次数与 numberOfLoans2 的值一样多。如果你不想要那个,移动你的

 String toDisplay = sb.toString();

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

在for循环之外。

于 2011-06-12T21:34:11.533 回答
0

在您的答案打印方法中,该numberOfLoans2变量用于两个地方:在 for 循环中进行多次打印(外循环)和在 for 循环中进行数学计算(内循环)。可能外面的那个没用了,所以去掉它,结果可能会显示一次。请记住删除}循环元素末尾的结尾以保持结构正常:)

于 2011-06-12T22:01:57.387 回答