我正在从事学校的ATM Java任务,我被困住了。在子类 Bank 中,我有一个HashMap变量, theBank ,方法 createAccount 用于添加到地图中。接口由赋值规范预先确定,包括HashMap的静态状态:
import java.util.HashMap;
public class Bank {
public static HashMap<String, BankCustomer> theBank;
public Bank ()
{
theBank = new HashMap<String, BankCustomer> ();
}
/**
* Method createAccount.
* To add a new BankCustomer element to the HashMap.
* Uses the account number as the key and the new BankCustomer as the value.
* @param newCustomer to input a BankCustomer for the HashpMap
*
*/
public void createAccount(BankCustomer newCustomer)
{
if (newCustomer != null){
theBank.put(newCustomer.getAccountNumber(), newCustomer);
}
}
我需要在主驱动程序类的方法中初始化HashMap:
/**
* Method initialize
* To add Customer references to the Bank HashMap as seed data for testing
*/
public void initialize()
{
Bank testBank = new Bank (); //initialize HashMap from Bank class
//seed the HashMap with a few objects
BankCustomer a = new BankCustomer("David", "Jones", "A001", "547");
BankCustomer b = new BankCustomer("Alice", "Stone", "A002", "777");
//seed the HashMap
testBank.createAccount(a);
testBank.createAccount(b);
}
这是驱动程序类的默认构造函数(run()方法是case / switch例程):
public class ATM {
/**
* Default constructor of class ATM.
* Calls the initialize() method to seed the Bank with some BankCustomers.
* Calls the run() method to perform the primary program functions.
*/
public ATM ()
{
initialize();
run();
}
主要的驱动方法是:
public static void main(java.lang.String[] args)
{
new ATM();
}
我的问题是在我的ATM类方法中,我无法访问Bank HashMap变量, testBank ; &#34; testBank无法解决。&#34;以下是testBank未解决的方法之一:
/**
* Method verifyCustomer
* To confirm a BankCustomer's account number and passcode.
* Called when the user is required to sign in to the application.
* Will set a boolean so the user does not have to sign in again during the session.
*/
public void verifyCustomer()
{
InputReader reader = new InputReader ();
boolean isVerified = false;
if(isVerified == false){
System.out.println("Enter Account Number: ");
String accountNumber = reader.getStringInput();
for(String accounts: testBank.keySet()){
if(accounts.equals(accountNumber)){
BankCustomer customer = testBank.get(accounts);
String code = customer.getPasscode();
System.out.println("Enter Passcode: ");
String passcode = reader.getStringInput();
if(code.equals(passcode)){
isVerified = true;
}
else{
System.out.println("Incorrect passcode.");
isVerified = false;
}
}
else{
System.out.println("Account not found.");
isVerified = false;
}
}
}
}
我是否正在初始化HashMap并在 initialize()方法中正确播种? 有什么建议 testBank 没有解决?如何使HashMap的范围足够宽,以便在ATM类方法中解决?
非常感谢。
答案 0 :(得分:0)
根据你在问题中所写的内容,我知道为什么会失败:
public void initialize(){
初始化HashMap
Bank testBank = new Bank(); //从Bank类
这是您的问题开始的地方。你是用你的本地方法创建的,但是你不能把它保存在任何地方。您需要具有私有参数或其他形式的体系结构。这根本不适用于编译时间。