В то время как цикл в ежемесячном калькуляторе амортизации работает после 0 [Java]

Я почти закончил программировать ежемесячный калькулятор амортизации, который основан на основной сумме пользователя, ежемесячном проценте и ежемесячном платеже. Но есть последняя проблема, которую я не могу понять. Я, кажется, установил лимит в 0, но он все еще показывает первую сумму, если отрицательные деньги были чем-то. Вот код для лучшего понимания того, что я имею в виду:

import java.util.Scanner;

public class Amortization {

   public static void main(String []args){

       Scanner input = new Scanner(System.in);
       int month = 1;
       int year = 0;

       double balance;
       double rate;
       double payment;
       double principal;
       double calculated_interest;
       double actual_payment;
       double principal_amt;

       System.out.println("What is your principal amount?"); principal = input.nextDouble(); balance = principal;
       System.out.println("What is your monthly interest rate in decimal?"); rate = input.nextDouble();
       System.out.println("What is your monthly payment?"); payment = input.nextDouble();


       while(balance>0){

          if(month == 13){
             year++;
             month = 1;
          }

          calculated_interest = ((int)(Math.round(balance*rate*100)))/100.0;
          principal_amt = ((int)(Math.round((payment-calculated_interest))*100))/100.0;
          actual_payment = ((int)(Math.round((payment-calculated_interest)*100)))/100.0;

          System.out.println("Year " + year + ", " + "Month " + month + ":");
          System.out.println("Your interest amount is " + "$" + calculated_interest);
          System.out.println("Your principal amount " + "$" + principal_amt);
          balance = ((int)(Math.round((balance-actual_payment)*100)))/100.0;

          System.out.println("Your new balance is " + "$" + balance);
          System.out.println();

          month++;
      }
      input.close();
     }
  }

2 ответа

Есть несколько проблем с вашим кодом.

  • Сумма процентов и основной выплаты каждого месяца не равна ежемесячной выплате.
  • "фактическая_плата", рассчитанная вами, не требуется.
  • Вам не нужно округлять платежи до целых чисел.
  • Поскольку вы принимаете ежемесячные платежи от пользователя, пользователь должен будет заплатить меньше, чем ежемесячный платеж в прошлом месяце, и это является причиной -ve. Если вы хотите, чтобы ваши платежи были равны каждый месяц, вам придется рассчитывать ежемесячные платежи самостоятельно.

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int month = 1;
        int year = 0;
    
        double balance;
        double rate;
        double payment;
        double principal;
        double calculated_interest;
        double actual_payment;
        double principal_amt;
    
        System.out.println("What is your principal amount?");
        principal = input.nextDouble();
        balance = principal;
        System.out.println("What is your monthly interest rate in decimal?");
        rate = input.nextDouble();
        System.out.println("What is your monthly payment?");
        payment = input.nextDouble();
    
        while (balance > 0) {
    
            if (month == 13) {
                year++;
                month = 1;
            }
            calculated_interest = (balance * rate * 100) / 100.0;
            principal_amt = payment - calculated_interest;
    
            System.out.println("Year " + year + ", " + "Month " + month + ":");
            System.out.println("Your interest amount is " + "$" + calculated_interest);
    
            if (balance > payment) {
    
                balance = ((int) (Math.round((balance - principal_amt) * 100))) / 100.0;
                System.out.println("Your principal amount " + "$" + principal_amt);
                System.out.println("Your new balance is " + "$" + balance);
            } else {
                System.out.println("Your principal amount " + "$" + (balance - calculated_interest));
                System.out.println("Your new balance is " + "$" + 0);
                System.out.println("You'll only pay $" + (calculated_interest + balance) + " this month.");
                break;
            }
    
            System.out.println();
    
            month++;
        }
        input.close();
    }
    

The problem is when the loop is at Year 29, month 12 the values are

Year 29, Month 12:
Your interest amount is $20.9
Your principal amount $4176.0
Your new balance is $3.45

Now, at this the value of balance не менее чем 0, так while будет верно, и когда новые значения будут рассчитаны баланс (balance = ((int)(Math.round((balance-actual_payment)*100)))/100.0;) становится отрицательным как balance - atual_payment will return negative because the previous balance is $3.45,

Одно из решений - добавить другое условие if в цикл while после вычисления баланса.

while(balance>0){

      calculated_interest = ((int)(Math.round(balance*rate*100)))/100.0;
      principal_amt = ((int)(Math.round((payment-calculated_interest))*100))/100.0;
      actual_payment = ((int)(Math.round((payment-calculated_interest)*100)))/100.0;
      balance = ((int)(Math.round((balance-actual_payment)*100)))/100.0;

      if (balance < 0){
        break; //this will break out of the loop
      }

      if(month == 13){
         year++;
         month = 1;
      }
      System.out.println("Year " + year + ", " + "Month " + month + ":");
      System.out.println("Your interest amount is " + "$" + calculated_interest);
      System.out.println("Your principal amount " + "$" + principal_amt);

      System.out.println("Your new balance is " + "$" + balance);
      System.out.println();

      month++;
  }

Этот код не распечатывает отрицательный баланс.

Другие вопросы по тегам