Амортизация кредита с использованием цикла с компонентами Java Swing. - PullRequest
0 голосов
/ 16 января 2012

Хорошо, я все еще новичок в Java, и я собираюсь на девятую неделю этого материала.Я собираюсь опубликовать некоторый исходный код из школьного проекта - это не весь источник - этот кусок кода - мой цикл для амортизации кредита.Я пытаюсь амортизировать из выбора меню (печать меню в текстовое поле) или из пользовательского ввода.Проблема в том, и я не могу понять, математика ли это, или мой цикл заключается в том, что он не амортизирует кредит должным образом.Я просто хочу знать, видит ли кто-нибудь что-то очевидное, что я пропустил, и если да, то не могли бы вы указать на это, чтобы я мог встать на правильный путь?Заранее спасибо!

ИСТОЧНИК:

private void amortizeButtonActionPerformed( java.awt.event.ActionEvent evt ) {
  // This module borrowed from Ryan Jones in George Griepp's PRG 420 class.

  NumberFormat nf = NumberFormat.getCurrencyInstance();
  int Monthly = 0;
  int monthcount = 0;
  String Output = "";

  int i = 0; // For first loop
  double loanamount = Double.parseDouble( tempTextField3.getText() );        //all loan amounts  are the same  
  double rate = Double.parseDouble( tempTextField1.getText() );     //Array for the rate
  double time = Double.parseDouble( tempTextField2.getText() );         //Array for the time
  double totalnumpayments = 0;         //Set for 
  double monthlypayment = 0; //Set for math calculation in first loop
  double interestPayment = 0;            //Set for math calculation in first loop
  double totaltime = 0; //Set for second loop to know how long to loop
  double loan = 0; //Set for second loop
  double interestPayment2 = 0; //Set for second loop
  double principlePayment = 0;  //Set for second loop


  for ( i = 0; i < time; i++ ) {//First loop This loops through the arrays and gives the first message listed below three times
    monthlypayment = ( loanamount * ( ( rate / 12 ) / ( 1 - Math.pow( ( 1 + ( rate / 12 ) ), -( time * 12 ) ) ) ) );
    interestPayment = loanamount * ( rate * 100 / 1200 );
    totaltime = ( time * 12 );


    jTextArea1.setText( "" );
    jTextArea1.setText( "This loan has an interest rate of " + ( rate * 100 ) + "%" + " and a starting loan amount of " + nf.format( loanamount ) );
    jTextArea1.setText( "Payment Number\t\t" + "Towards Principle\t\t" + "Towards Interest\t" + "Remaining on loan" );
    jTextArea1.setText( "" ); // Part of the first loop this will appear three times with the math listed above


    System.out.println( totaltime );
    Monthly++;

    Output += ( ( monthcount++ ) + "\t\t\t" + nf.format( principlePayment ) + "\t\t\t" + nf.format( interestPayment2 ) + "\t\t\t" + nf.format( loan - principlePayment ) + "\n" );


    loan = -principlePayment;// Changes the numbers as the loop goes
    interestPayment2 = loan * ( rate * 100 / 1200 );// Changes the numbers as the loop goes
    principlePayment = monthlypayment - interestPayment2;// Changes the numbers as the loop goes

  }
  jTextArea1.setText( Output );
}

1 Ответ

2 голосов
/ 16 января 2012

Есть несколько вещей, которые могут быть проблемой или нет (я не знаком с математикой, стоящей за займами ).

  1. Вы вычислили totaltime в своем for -цикле, не используя переменную i. Следовательно, это всегда будет приводить к одному и тому же результату и может быть вычислено вне цикла
  2. Вызвав setText на jTextArea1 внутри цикла, где ваш последний вызов с пустым String, вы можете также очистить его перед входом в for -loop, как в конце jTextArea1 будет просто пустым. Или просто удалите код, так как после цикла for вы устанавливаете текст Output
  3. loan = -principlePayment - странное утверждение. Так что если principlePayment - положительное число, loan будет отрицательным числом, а interestPayment2 также
  4. Вам лучше использовать StringBuilder для построения вашей Output переменной

Я думаю, что номер 3 является наиболее важным для ваших расчетов.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...