好的,所以我完成了我的代码,或者我认为,但它没有加载我必须阅读的csv文件中的帐号。我完全迷失了,不理解为什么它不会将这些帐户读入组合框中。有人可以帮我弄清楚为什么帐户没有出现在组合框中。以下是运行程序的Controller Package:
import edu.tridenttech.cpt237.bank.model.Bank;
import edu.tridenttech.cpt237.bank.view.StartWindow;
import javafx.application.Application;
import javafx.stage.Stage;
public class MainApp extends Application
{
@Override
public void start(Stage primaryStage) throws Exception
{
Bank bank = new Bank();
bank.loadTransactions("Transactions.csv");
StartWindow ui = new StartWindow(primaryStage);
ui.show();
}
public static void main(String [] args)
{
Application.launch(args);
}
}
以下是Model Package中的Bank类:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
public class Bank
{
private static Bank instance = new Bank();
private ArrayList<Account> accounts = new ArrayList<>();
/**
* Gets the Singleton Bank instance
* @return Returns the singleton Bank instance
*/
public static Bank getInstance()
{
return instance;
}
/**
* Open a new savings account and place it in the list of bank accounts.
*
* @param accntNum the number of the new account
* @param initialBal the initial balance
* @return Returns <i>true</i> if an account is created; <i>false</i> if the account already exists or the balance is invalid
*/
public boolean openSavingsAccount(String accntNum, double initialBal)
{
if (findAccountByNum(accntNum) != null || initialBal < 0) {
return false;
}
SavingsAccount savings = new SavingsAccount(accntNum, initialBal);
return accounts.add(savings);
}
/**
* Open a new checking account and place it in the list of bank accounts.
*
* @param accntNum the number of the new account
* @param initialBal the initial balance
* @return Returns <i>true</i> if an account is created; <i>false</i> if the account already exists or the balance is invalid
*/
public boolean openCheckingAccount(String accntNum, double initialBal, double minBalance)
{
if (findAccountByNum(accntNum) != null || initialBal < 0) {
return false;
}
CheckingAccount checking = new CheckingAccount(accntNum, initialBal);
return accounts.add(checking);
}
/**
* Finds the account specified by the given account number
* @param accntNum the number of the account to be found
* @return Returns the account matching the number if found; <i>null</i> if the account is not found
*/
public Account findAccountByNum(String accntNum)
{
Account acnt = null;
Optional<Account> match = accounts.stream().filter(e -> e.getAccountNumber().equals(accntNum)).findFirst();
if (match.isPresent()) {
acnt = match.get();
}
return acnt;
}
/**
* Transfers the specified amount from the fromAccount to the toAccount. This method can fail if either
* of the account numbers is invalid, or if the fromAccount has insufficient funds to make the transfer.
* @param fromAccountNum The account number of the account from which the money is to be withdrawn.
* @param toAccountNum The account number of the account to which the money is to be deposited.
* @param amount The amount to be transfered.
* @return Returns <i>true</i> if the transfer was successful, <i>false</i> otherwise
*/
public boolean makeTransfer(String fromAccountNum, String toAccountNum, double amount)
{
Account fromAccnt;
Account toAccnt;
fromAccnt = findAccountByNum(fromAccountNum);
toAccnt = findAccountByNum(toAccountNum);
if (fromAccnt == null || toAccnt == null) {
return false;
}
if (fromAccnt.withdraw(amount)) {
toAccnt.deposit(amount);
return true;
} else {
return false;
}
}
/**
* Pulls all of the account numbers from the accounts and returns them as a list of strings.
* @return The list of account numbers.
*/
public List<String> getAllAccountNumbers()
{
ArrayList<String> accountNums = new ArrayList<>();
accounts.stream().forEach(e -> accountNums.add(e.getAccountNumber()));
return accountNums;
}
/**
* Loads the transactions from the specified comma separated values file. The format of the file is as follows:
* O,num,type,amount
* D,num,type,amount
* W,num,type,amount
* T,from,to,amount
* @param filePath Path to the file containing the transactions
* @throws FileNotFoundException
*/
public void loadTransactions(String filePath) throws FileNotFoundException
{
Scanner input;
input = new Scanner(new File(filePath));
while (input.hasNext())
{
String line = input.nextLine();
// creates an string array called fields and populates each item
// splitting by comma.
String[] fields = line.split(",");
// System.out.println("number of fields: " + fields.length);
// first field and first character
switch (fields[0].charAt(0)) {
case 'O':
case 'o': {
double minBalance = 0;
// open a new account
String accntNum = fields[1];
String type = fields[2];
double initialBalance = Double.parseDouble(fields[3]);
if (fields.length == 5)
{
minBalance = Double.parseDouble(fields[4]);
}
createAccount(accntNum, type, initialBalance, minBalance);
} break;
case 'D':
case 'd': {
// deposit into an account
String accntNum = fields[1];
String type = fields[2];
double amount = Double.parseDouble(fields[3]);
Account account = findAccountByNum(accntNum);
account.deposit(amount);
} break;
case 'W':
case 'w': {
String accntNum = fields[1];
String type = fields[2];
double amount = Double.parseDouble(fields[3]);
Account account = findAccountByNum(accntNum);
account.withdraw(amount);
} break;
case 'T':
case 't': {
String fromAccount = fields[1];
String toAccount = fields[2];
double amount = Double.parseDouble(fields[3]);
makeTransfer(fromAccount, toAccount, amount);
} break;
default: {
System.out.println("Does not meet requirements");
}
}
}
input.close();
}
private void createAccount(String accntNum, String type, double initialBalance, double minBalance)
{
switch (type.charAt(0)) {
case 's':
case 'S': {
openSavingsAccount(accntNum, initialBalance);
} break;
case 'c':
case 'C': {
openCheckingAccount(accntNum, initialBalance, minBalance);
} break;
}
}
}
最后一个类是View Package中的StartWindow:
import edu.tridenttech.cpt237.bank.model.Bank;
import edu.tridenttech.cpt237.bank.view.NewAccount;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class StartWindow implements EventHandler<ActionEvent>
{
private Stage myStage;
private Transaction transaction;
private NewAccount account;
private Transfer t;
private ComboBox<String> AccountsCB = new ComboBox<>();
Button display;
Button open;
Button transfer;
Button exit;
public StartWindow(Stage stage)
{
transaction = new Transaction();
FlowPane pane = new FlowPane();
Scene scene = new Scene(pane);
myStage = stage;
myStage.setScene(scene);
myStage.setTitle("Starting Window");
pane.getChildren().add(AccountsCB);
AccountsCB.getItems().setAll(Bank.getInstance().getAllAccountNumbers());
account = new NewAccount(AccountsCB);
display = new Button("Display Current Account");
pane.getChildren().add(display);
display.setOnAction(this);
open = new Button("Open New Account");
pane.getChildren().add(open);
open.setOnAction(this);
transfer = new Button("Transfer Funds Between Accounts");
pane.getChildren().add(transfer);
transfer.setOnAction(this);
t = new Transfer();
exit = new Button("Exit");
pane.getChildren().add(exit);
exit.setOnAction(this);
}
public void handle(ActionEvent event)
{
Button button = (Button) (event.getSource());
if (button == display)
{
if (!transaction.isShowing())
{
transaction.show(AccountsCB.getValue());
}
else
{
transaction.toFront();
}
}
if (button == open)
{
if (!account.isShowing())
{
account.show();
}
else
{
account.toFront();
}
}
if (button == transfer)
{
if (!t.isShowing())
{
t.show();
}
else
{
t.toFront();
}
}
if (button == exit)
{
myStage.close();
}
}
public void show()
{
myStage.show();
}
}
当我运行该程序时,它允许我创建一个新帐户,但是当我想在帐户之间转移资金或打开现有帐户时,它不会从Transactions.csv文件中加载帐户。
答案 0 :(得分:0)
您正在尝试将Bank
实现为单身,但您没有阻止创建Bank
的其他实例。因此,在start()
方法中,您可以创建Bank
的新实例并在该实例中加载事务:
Bank bank = new Bank();
bank.loadTransactions("Transactions.csv");
显然,这与Bank
返回的Bank.getInstance()
的实例不同,因此在您的StartWindow
课程中,当您致电Bank.getInstance()
时,您会收到Bank
1}}没有加载任何事务的实例。
如果你想让Bank
成为单身,你应该将构造函数设为私有,以防止创建任何其他实例:
public class Bank {
private static Bank instance = new Bank();
private ArrayList<Account> accounts = new ArrayList<>();
/**
* Gets the Singleton Bank instance
* @return Returns the singleton Bank instance
*/
public static Bank getInstance() {
return instance;
}
// private constructor:
private Bank() { }
// existing code....
}
然后当然做
@Override
public void start(Stage primaryStage) throws Exception {
Bank.getInstance().loadTransactions("Transactions.csv");
StartWindow ui = new StartWindow(primaryStage);
ui.show();
}
许多程序员的单例模式是generally considered an anti-pattern。我建议只以通常的方式创建一个Bank
实例并将其传递给StartWindow
实例(以及其他需要它的实例):
public class Bank {
// private static Bank instance = new Bank();
private ArrayList<Account> accounts = new ArrayList<>();
/**
* Gets the Singleton Bank instance
* @return Returns the singleton Bank instance
*/
// public static Bank getInstance() {
// return instance;
//}
/**
* Open a new savings account and place it in the list of bank accounts.
*
* @param accntNum the number of the new account
* @param initialBal the initial balance
* @return Returns <i>true</i> if an account is created; <i>false</i> if the account already exists or the balance is invalid
*/
public boolean openSavingsAccount(String accntNum, double initialBal)
{
if (findAccountByNum(accntNum) != null || initialBal < 0) {
return false;
}
SavingsAccount savings = new SavingsAccount(accntNum, initialBal);
return accounts.add(savings);
}
// existing code ...
}
然后创建银行实例,加载其交易,并将其传递给您的StartWindow
:
public class MainApp extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Bank bank = new Bank();
bank.loadTransactions("Transactions.csv");
StartWindow ui = new StartWindow(primaryStage, bank);
ui.show();
}
public static void main(String [] args) {
Application.launch(args);
}
}
和
public class StartWindow implements EventHandler<ActionEvent> {
private Bank bank ;
private Stage myStage;
private Transaction transaction;
private NewAccount account;
private Transfer t;
private ComboBox<String> AccountsCB = new ComboBox<>();
Button display;
Button open;
Button transfer;
Button exit;
public StartWindow(Stage stage, Bank bank) {
this.bank = bank ;
transaction = new Transaction();
FlowPane pane = new FlowPane();
Scene scene = new Scene(pane);
myStage = stage;
myStage.setScene(scene);
myStage.setTitle("Starting Window");
pane.getChildren().add(AccountsCB);
// note:
AccountsCB.getItems().setAll(bank.getAllAccountNumbers());
account = new NewAccount(AccountsCB);
display = new Button("Display Current Account");
pane.getChildren().add(display);
display.setOnAction(this);
open = new Button("Open New Account");
pane.getChildren().add(open);
open.setOnAction(this);
transfer = new Button("Transfer Funds Between Accounts");
pane.getChildren().add(transfer);
transfer.setOnAction(this);
t = new Transfer();
exit = new Button("Exit");
pane.getChildren().add(exit);
exit.setOnAction(this);
}
// etc ...
}