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

「比較するローンのリスト」は、オブジェクトの配列によって表されます...つまり、各「ローン オプション」は、特定のローンのすべての属性を 1 つのきちんとした「もの」にグループLoan化するクラスのインスタンスによって表されます。Loanその後、全体として操作できます。これは、「並列配列」と呼ばれるローン属性を保存するために使用している手法よりも優れたアプローチです...そして、うーん、少し時代遅れです。実際には、(脂っこい)ボラがあり、 (きつすぎる) オレンジ色のサファリ スーツに (サフラン ピンク) のヘッドバンド. あなたのロケールに応じて...基本的に:私たちは今より良い方法を持っています!

このLoanクラスには、計算を行うための便利な「計算フィールド」もいくつかあります。これは、返済を計算する方法が将来何らかの理由で変更された場合、それを変更する場所が 1 か所しかないことを意味し、ローンを使用するすべてのもの (読み取り、書き込み、並べ替え、合計、回収、またはローンの卸売りなど) は変更を行います。変更する必要はありません...彼らは「無料で」変更を受け取るだけです。

この不自然なユースケースでは、すべてのローンは同じ金額で、金利と期間のみが異なります...そのため、Loanクラスにはstatic「原則」と呼ばれる変数もあり、これは、のすべてのインスタンスに「共通」の原則を保持しますローンクラス。原則は一度しか設定できません。その後、原則を設定しようとすると、ReadOnlyException がスローされます。

とにかく、この演習を自分で行っている間に発見した可能性のあるサブ問題のいくつかに取り組むための別の方法を見て、何かを学んでいただければ幸いです. 将来のための 1 つのヒント: この演習用のクラスメートのコードを取得して、それを読んでください。他の人がどのように取り組んでいるかから、多くのことを学ぶことができます。

乾杯。キース。

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

あなたは私たちに問題が何であるかを教えてくれませんでしたが、私はこのビットがあなたが望むことをしているとは思いません。ループが一周するたびに、3つの配列全体を出力するようにプログラムに要求しています。代わりに、ローンごとに特定の配列要素にアクセスしたいと思うでしょう。何かのようなもの...

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変数は2つの場所で使用されます。印刷を何度も行うforループ(外側のループ)と、数学的な計算を行うforループ(内側のループ)です。たぶん外側は使い物にならないので外して、一度結果を出してもいいかもしれません。構造を適切に保つために、ループ要素の最後にあるエンディングを削除することを忘れないでください}:)

于 2011-06-12T22:01:57.387 に答える