我的任務有一種方法出現問題。這是此方法的要求:數組未顯示(Java)
「此方法使用循環列出陣列中包含的所有帳戶,將每個帳戶詳細信息添加到字符串,然後以下面屏幕截圖中指定的格式輸出到屏幕。通過檢查每個數組插槽是否有一個帳戶對象,然後將其詳細信息添加到輸出String(arrayname [index]!= null),確保沒有越界異常「
這是我的代碼方法:
public void listAllAccounts()
{
String allAccountsString = "List of all accounts: \n";
for(int i = 0; i < ACCOUNT_SPACES; i++)
{
//allAccountsString += accountArray[numAccounts];
if (accountArray[i] !=null)
{
allAccountsString += accountArray[i].toString() + "\n\n" ;
}
}
JOptionPane.showMessageDialog(null, allAccountsString);
問題是,消息對話框不顯示我已經創建的帳戶。它只是顯示"List of all accounts: \n";
任何想法?
這是整個類的代碼:
public class MyBankController
{
/**
* Variables that will be used by this class
*/
private BankAccount newAccount;
private BankAccount accountArray[];
int numAccounts = 0;
int ACCOUNT_SPACES = 2;
private boolean accountStatus = false;
/**
* Constructor for objects of class MyBankController - to be left empty by requirements.
*/
public MyBankController()
{
//
}
/**
* A method to create a new account, accepting user input and allocating memory space.
*/
public void createAccount(String customerName, int accountNumber)
{
newAccount = new BankAccount(customerName, accountNumber);
accountArray = new BankAccount [2];
if(numAccounts +1 <= ACCOUNT_SPACES)
{
numAccounts++;
printAccountDetails();
}
else
{
JOptionPane.showMessageDialog(null, "Sorry, a maximum limit of accounts allowed has been reached." + "\n" + "Limit: " + numAccounts + "/10", "Warning!", JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* Method to print the account details - by calling an object from the BankAccount class.
*/
private void printAccountDetails()
{
JOptionPane.showMessageDialog(null, newAccount.toString(), "Account Details", JOptionPane.INFORMATION_MESSAGE);
}
public void listAllAccounts()
{
String allAccountsString = "List of all accounts: \n";
for(int i = 0; i < ACCOUNT_SPACES; i++)
{
if (accountArray[i] !=null)
{
allAccountsString += accountArray[i].toString() + "\n\n" ;
}
JOptionPane.showMessageDialog(null, allAccountsString);
}
}
public void listAllOpenAccounts()
{
String allAccountsString = "List of all accounts: \n";
for(int i = 0; i < ACCOUNT_SPACES; i++)
{
//allAccountsString += accountArray[numAccounts];
if (accountArray[i] !=null && accountStatus == true)
{
allAccountsString += accountArray[i].toString() + "\n\n" ;``
}
}
JOptionPane.showMessageDialog(null, allAccountsString);
}
}
我想,'accountArray [I]'總是空。 – 2015-02-10 12:57:56
Account_spaces的值是什麼,另外爲什麼你不使用accountArray.length,以及這個數組有什麼來源,因爲它在代碼示例中不可見。 – SomeJavaGuy 2015-02-10 12:58:09
您可以嘗試在for循環之前打印出accountsArray [0],以查看是否真的存在隱藏的內容 – Johan 2015-02-10 13:05:16