2011-12-06 6 views
2

私は現在、ユーザーローン金額、年間利息、および月額支払いから次の情報を得るべきwhileループに取り組んでいます。毎月の利息と毎月の支払額を比較し、最初の1ヶ月分の利息が指定された支払額を上回っているか等しい場合は、毎月の支払額が利息よりも高くなるまでダイアログを開きます。whileループを使用してローンの支払いを毎月の利息 - ロジックエラーと比較する

特定のケースで(私がローンに1000を入力し、12%の利子と121を下回る支払いをした場合、プログラムはより大きな支払いを要求します)。しかし、ローン金額と毎月のお支払い金額を入力すると(500ローンの金額は毎月400回支払われます)、十分な金額を入力していないというエラーダイアログが表示されます。 ハァッ!

ここに私のコードがあります。ありがとう!

package program6; 
import javax.swing.JOptionPane; 

public class LoanAmount2 { 

    public static void main(String[] args) { 
     String loanAmountString = JOptionPane.showInputDialog(null, "Enter the amount for your loan."); 
     double loanAmount = Double.parseDouble(loanAmountString); 
     String annualInterestString = JOptionPane.showInputDialog(null, "Enter your annual interest rate."); 
     double annualInterestRate = Double.parseDouble(annualInterestString); 
     annualInterestRate = 1 + (annualInterestRate/100); 
     String monthlyPaymentString = JOptionPane.showInputDialog(null, "Enter the amount for your monthly payment."); 
     double monthlyPayment = Double.parseDouble(monthlyPaymentString); 
     double monthlyInterestRate = 1 + (annualInterestRate/12); 
     double monthlyInterest = loanAmount * monthlyInterestRate; 
     while (monthlyInterest >= monthlyPayment) { 
      monthlyPaymentString = JOptionPane.showInputDialog(null, "Your payment only covers the interest on your loan. Please enter a larger amount for your monthly payment."); 
      monthlyPayment = Double.parseDouble(monthlyPaymentString); 
      break; 
     } 

} 

}

答えて

2

私はこのスクリプトを実行し、あなたの問題に気づきました。ライン:

double monthlyInterestRate = 1 + (annualInterestRate/12); 

は次のようになります。

double monthlyInterestRate = annualInterestRate/12; 

あなたは常にtrueと評価されますこれはあなたのwhileループに1を追加した場合、あなたが1.xxの

+0

ありがとう!私は – user1082706

0
でフル融資額を乗じているので、

この問題をより小さな部分に分割しようとすることをお勧めします。あなたがプログラムの中でこのパターンを数回繰り返します。

String annualInterestString = 
     JOptionPane.showInputDialog(null, 
        "Enter your annual interest rate."); 
    double annualInterestRate = 
     Double.parseDouble(annualInterestString); 

は、私はあなたが以下のような方法で提供されている場合、あなたのコードを読むために容易になるだろうと思う:

double prompt_for_number(String prompt) { 
    /* show dialog box */ 
    /* parse string into a Double */ 
    /* return number */ 
} 

これはあなたが聞かせ再書き込みあなたのコードは次のようになります。

loanAmount = prompt_for_number("Enter the amount for your loan."); 
annualInterestRate = prompt_for_number("Enter your annual interest rate."); 

これにより、計算の流れがわかりやすくなります。 (そして実際のエラーを起こして、あなたがここに来て、見つけやすくなりました。)

+0

大きなアドバイスを感謝します。私はまだ私のプログラミングのレベルにはまだ(メソッドに達していない)だとは思わないが、私は心に留めておくつもりだ、ありがとう – user1082706

関連する問題