我是编程新手,第一次使用对象数组。
我有一个叫做 Account 的类,它代表一个银行账户。在我的 ATM 机器类的 main 方法中,我创建了一个 Account 对象数组。我通过静态方法用实例化的对象填充数组。
我有两个额外的静态方法(一个打印出数组,我将其用于测试,另一个假设检查银行帐户 ID 是否有效)。当 Account 对象数组传递给这些各自的静态方法时,这两个静态方法都会抛出空指针异常。
当我注释掉这两个静态方法时,一切正常。任何帮助,将不胜感激。代码如下:
package banking;
import java.util.Scanner;
public class AtmMachine {
public static void main(String[] args) {
//Create account array of size 10
Account[] bankAccounts = new Account[10];
//Create 10 accounts
createAccounts(bankAccounts);
/*
//PROBLEM AREA
//Print Bank Accounts
printAccounts(bankAccounts);
*/
//Menu
menu(bankAccounts);
}
public static void createAccounts(Account[] bankAccounts) {
for (int i = 1; i < bankAccounts.length; i++) {
bankAccounts[i] = new Account(i, 100);
}
}
public static void menu(Account[] bankAccounts) {
//Create Scanner object
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter your account number: ");
int accountNumber = input.nextInt();
//THIS IS THE PROBLEM
/*
//Check to see if a valid account
if (!isAccount(accountNumber, bankAccounts)) {
System.out.println("You entered a wrong account number. Try again.");
continue;
}
*/
//Enter the menu of the account system
accountMenu(bankAccounts[accountNumber]);
}
}
//THE PROBLEM METHOD
public static boolean isAccount(int account, Account[] bankAccounts) {
for (int i = 0; i < bankAccounts.length; i++) {
if (bankAccounts[i].getId() == account) {
return true;
}
}
return false;
}
POPMUISE
相关分类