Создание метода вывода средств для вывода денег с активного счета с балансом. Консоль показывает значение вывода, правильно переданное из TestClass в класс учетной записи, где определен метод вывода. Он также показывает значение изменения «баланса» внутри метода вывода.
Однако, когда я вызываю значение баланса в моей следующей строке кода, он дает мне начальное значение баланса, когда я создал учетную запись.
Я включу то, что кажется важным:
Вот суперкласс
public class Account {
//declares the variables
private double initialBalance;
private double credit;
private double balance;
//default constructor
public Account() {
this(0.0, 0.0);
}
//constructs Account object
public Account(double initialBalance, double balance) {
this.initialBalance = initialBalance;
this.balance = initialBalance;
}
//gets initial balance
public double getInitialBalance() {
return initialBalance;
}
//gets balance
public double getBalance() {
return balance;
}
// Sets initial balance
public void setInitialBalance(double initialBalance) {
if (initialBalance > 0){
this.initialBalance = initialBalance;
this.balance = initialBalance;
}
else noCrediting();
}
//crediting the account if the credit function gets a positive input
public double credit(double creditInput, double balance){
if (creditInput>0)
{
balance = balance + creditInput;
}
else
noCrediting();
return balance;
}
//tells the user no credit was added
public void noCrediting() {
System.out.println("No credit was added because the deposit was not a positive double.");
}
//withdrawing from the account if the function gets a positive input
public void withdraw(double withdrawInput, double balance){
if (withdrawInput>0 && withdrawInput<balance)
{
balance = balance - withdrawInput;
}
else
noWithdrawing();
}
//tells the user no withdrawal was performed
public void noWithdrawing() {
System.out.println("No amount was withdrawn because the deposit was not a positive double less than the balance.");
}
}
Вот подкласс
public class CheckingAccount extends Account {
//declares the variables
private double feeChargedPerTransaction = 2.0;
//default constructor
public CheckingAccount() {
this(0.0, 0.0, 2.0);
}
//constructs Account object
public CheckingAccount(double initialBalance, double balance, double feeChargedPerTransaction) {
super(initialBalance, balance);
feeChargedPerTransaction = 2.0;
}
//withdrawing from the account if the function gets a positive input
public void withdraw(double withdrawInput, double balance){
if (withdrawInput>0 && withdrawInput < balance)
{
System.out.println("The withdrawal amount from the checking account class is showing"+ withdrawInput);
balance = (balance - withdrawInput)*.98;
System.out.println("Now The balance from the checking account class is showing: " + balance);
}
else
noWithdrawing();
}
//gets fee
public double getFee() {
return feeChargedPerTransaction;
}
public void noWithdrawing() {
System.out.println("No amount was withdrawnnn because the deposit was not a positive double less than the balance.");
}
}
Вот вызываемый метод
//withdrawing from the account if the function gets a positive input
public void withdraw(double withdrawInput, double balance) {
if (withdrawInput>0 && withdrawInput < balance) {
System.out.println("The withdrawal amount from the checking account class is showing"+ withdrawInput);
balance = (balance - withdrawInput)*.98;
System.out.println("Now The balance from the checking account class is showing: " + balance);
}
else
noWithdrawing();
}
Я добавил печать в консоль, чтобы следить за тем, что происходит, поскольку все это печатается через javaFX в моем testClass.
String test = "current balance is: "
+ findCheckingAccountIndex(s, checkingsArray, nameListChecking).getBalance();
System.out.println(test);
test = "withdraw amount: " + Double.parseDouble(transactionField.getText());
System.out.println(test);
вот где он находит счет и снимает с него с помощью снятия (двойной вывод, двойной баланс)
findCheckingAccountIndex(s, checkingsArray, nameListChecking).withdraw(Double.parseDouble(transactionField.getText()),findCheckingAccountIndex(s, checkingsArray, nameListChecking).getBalance());
здесь геттер должен показать изменение!
test = "new balance is: " + findCheckingAccountIndex(s,checkingsArray,nameListChecking).getBalance();
System.out.println(test);
Теперь скажем, я делаю счет, чтобы иметь 12 долларов. Я ввожу сумму вывода 11, и вот что вы обнаружите:
Распечатка из тестового класса, показывающая снятие средств, которое должно быть пройдено, и значение, полученное при получении баланса:
current balance is: 12.0
withdraw amount: 11.0
Печать из соответствующего подкласса во время выполнения блока метода:
The withdrawal amount from the checking account class is showing 11.0
Now The balance from the checking account class is showing: 0.98
Большой! Теперь показано значение, полученное от геттера, который вызывается после метода изъятия, и, следовательно, значение должно быть 0,98:
new balance is: 12.0
как вы можете видеть, новый баланс не устанавливается в методе вывода средств. Любые идеи? Возможная проблема передачи по значению? может быть, это связано с моим конструктором? Действительно потерял. Я должен понять это, чтобы я мог написать три других метода, которые также используют баланс.
((SuperClass) this).field
, но гораздо лучше дать полю другое имя, чтобы избежать путаницы. - person Peter Lawrey   schedule 25.07.2015