2015-03-10 2 views
0

Я работаю над назначением банковского счета. Похоже, я правильно понял логику, но не дает правильного вывода. Я думаю, что цикл не понимает, что я пытаюсь сказать ему. Я помещаю методы, вызванные не в том месте? Я приложил образец вывода. Я ценю вашу помощь! СпасибоКак мне исправить мой цикл?

/** 
* This program prints a payoff schedule for a bank customer. 
    Input: Account number, name of customer, and account balance. 
    Output: Prints payoff schedule that includes payment amount and new balance 
    until the account will be paid off. A customer must pay off their account when 
    the balance reaches $10 or less. 1.2% interest is added at the beginning of 
    each month and the customer then makes a payment equal to 5% of the current balance. 
    */ 

public class DT_BankAccount 
{ 
private String accountNum; 
private String customerName; 
private double customerBalance; 
double interest = 0.00; // Start out with 0.00 value for the customer. 
double payment = 0.00; // Start out with 0.00 value for the customer. 

/** 
* Constructor: Constructs a payoff schedule for a bank customer including account number, name of customer, and account balance. 
* @param account number - the account number of the customer 
* @param name of customer - the customer's name of the bank account 
* @param account balance - the account balance of the customer 
*/ 

public DT_BankAccount(String accountNum, String customerName, double customerBalance) 
{ 
// Initialize constructors 
    this.accountNum = accountNum; 
    this.customerName = customerName; 
    this.customerBalance = customerBalance; 
} 

/** 
    * This method calculates interest and return the balance times the 1.2% interest: the balance times the 1.2% interest 
    * @return the balance times the 1.2% interest 
    */ 
public double CalculateInterest() 
{ 
    return interest = customerBalance * 0.012; 
} 

    /** 
    * This method calculates new balance adds the interest to the balance 
    */ 
public void CalculateNewBalance() 
{ 
    payment = customerBalance + interest; 
} 

/** 
    * This method calculates new payment returns the balance times 5%: the balance times 5% 
    * @return the balance times 5% 
    */ 
public double CalculatePayment() 
{ 
    return payment * 0.05; 
} 

/** 
    * This method updates the balance after the payment is made: the updated (newest) balance 
    * @return the updated (newest) balance 
    */ 
public double BalanceUpdated() 
{ 
    return customerBalance = customerBalance + interest - payment; 
} 
} 

import javax.swing.JOptionPane; // import JOptionPane class 

public class DT_PayoffTester 
{ 
public static void main(String args[]) 
{ 
    // Declare and initialize variables. 
    String accountNum; 
    String customerName; 
    String stringCustomerBalance; 
    double customerBalance = 0.00; 
    double controller = 10.00; // Controls while loop. 


    // Get input. 
    accountNum = JOptionPane.showInputDialog("Enter account number: "); 
    customerName = JOptionPane.showInputDialog("Enter customer's name: "); 
    stringCustomerBalance = JOptionPane.showInputDialog("Enter customer's balance: "); 

    // Convert string to double. 
    customerBalance = Double.parseDouble(stringCustomerBalance); 

    // creates one instance of the BankAccoount class by calling it’s constructor. 
    DT_BankAccount BA = new DT_BankAccount(accountNum,customerName,customerBalance); 

    System.out.println(customerName + "\n"); 

    while (BA.BalanceUpdated() > controller) 
    { 
     // methods called 
     BA.CalculateInterest(); 
     BA.CalculateNewBalance(); 
     BA.CalculatePayment(); 
     BA.BalanceUpdated(); 
     System.out.println("Payment: " + BA.CalculatePayment()); 
     System.out.println("New Balance: " + BA.BalanceUpdated() + "\n"); 
    } // End of while loop. 
    System.out.println("Account Number: " + accountNum); 
    System.out.println("Final Balance Amount: " + BA.BalanceUpdated()); 
    System.out.println("Loan Paid Off"); 

    System.exit(0); 
    } 
    } 

Пример вывода:

Start of sample output 
Billie Gates 
Payment: $12.02 
New Balance: $228.39 
Payment: $11.56 
New Balance: $219.57 
Payment: $11.11 
New Balance: $211.09 
Payment: $10.68 
New Balance: $202.95 
Payment: $10.26 
New Balance: $195.11 
Payment: $9.87 
New Balance: $187.58 
Payment: $9.49 
New Balance: $180.34 

Перейти к концу выхода образца:

Payment: $ 0.62 
New Balance: $11.92 
Payment: $ 0.60 
New Balance: $11.46 
Payment: $0.58 
New Balance: $11.02 
Payment: $0.55 
New Balance: $10.59 
Payment: $0.53 
New Balance: $10.18 
Payment: $0.51 
New Balance:$ 9.79 
Account Number: 91234567 
Final Balance Amount:$ 9.79 
Loan Paid Off 

Мой вывод (неправильный)

Billie Gates 

Payment: 6.229872 
New Balance: -123.12 

Account Number: 123 
Final Balance Amount: -369.36 
Loan Paid Off 
+0

Когда 'BA.BalanceUpdated()' <= 10.00, ваш цикл остановится, это логика, которую вы хотели? Первый возвращенный баланс уже равен <= 10.00 (это '-123.12'). Можно сделать много улучшений, например. сохраните возвращаемое значение переменной вместо вызова 'BA.BalanceUpdated()' несколько раз. – Raptor

+0

Я не знаю, почему первый новый баланс является отрицательным числом! –

+0

Не вводите этого пользователя? – Raptor

ответ

1

Здесь приходит математика:

Входной сигнал: 237,56

Цикл 1:

В BA.BalanceUpdated() из while петли, customerBalance установлен в customerBalance, так как interest и payment по-прежнему 0. customerBalance является 237,56, который является> 10.00, петля продолжается.

В BA.CalculateInterest(), interest установлен на 237.56 х 0,012 = 2.85072

В BA.CalculateNewBalance(), payment установлен на 237.56 + 2.85072 = 240.41072

В BA.CalculatePayment(), он не делает ничего на первом вызове (как вы не используете возвращаемое значение).

Во втором BA.CalculatePayment() он возвращается к 240.41072 x 0.05 = 12.020536, но не присваивает какой-либо переменной.

В вашей печатной линии 2 BA.BalanceUpdated(), customerBalance устанавливается на 240.41072 + 2,85072 - 240.41072 = 2,85072

Loop 1 Complete

Тогда ваши while проверяет BA.BalanceUpdated() возвращается> 10.00, при этом момент, когда вы выполнили эту функцию 2-го раза, который установил customerBalance - 2.85072 + 2.85072 - 240.41072 = -234.70928, что равно < 10.00. while петлевые перерывы.

Таким образом, проверьте свою математическую логику.

0

Первая точка:

В таком случае, как это мое общее предложение было бы выполнить «проверку стол»; вручную выполните свой код на некоторых образцах данных, используя ручку и бумагу. То есть, начиная с некоторого значения, пройдите через свой код и для каждой строки выполните вычисления и запишите состояние всех переменных после каждой строки. Это может занять много времени, но оно работает.

Второй пункт:

Кажется, вы не можете понять, что каждый раз, когда вы звоните BalanceUpdated() значение customerBalance будет изменено. Если вы вызываете метод в состоянии цикла или если вы вызываете его в пределах System.out.println(), он все равно изменяет значение. К концу однократного выполнения этого цикла цикл интереса был добавлен и оплата вычитается три раза.

Смежные вопросы