2014-10-03 46 views
1

所以我必須爲學校設計一個簡單的銀行業務程序,並且我無法檢查我的陣列是否有特定的帳號。(首次編程)如何檢查某個特定值的類的數組?

基本信息,而不是全碼:

public class Account { 

    public String name; 
    int number; 
    double Balance; 

    private Account [] accounts; 


    public Account[] getAccounts() { 


     return accounts; 
    } 

    public boolean hasAccountNumber(int accountNumber) { 

     // How do I check my array of type Account if it has the passed in account number? 
     // I was trying to use the following: 

     Account[] b = getAccounts(); 
     if(Arrays.asList(b).contains(accountNumber)){ 
      return true; 
     } else{ 
      return false; 
     } 

    }  
} 

爲什麼不是這方面的工作?

+0

爲什麼要轉換爲列表?爲什麼不使用列表?任何你不使用列表的原因? – Tirath 2014-10-03 18:59:48

+0

什麼是錯誤,或堆棧跟蹤顯示? – Rika 2014-10-03 19:00:35

+0

如何比較'整個帳戶'對象? – Seitaridis 2014-10-03 19:12:52

回答

0

因爲數組b的元素是對象,而accountNumberint(原始)。 必須遍歷數組b,並將陣列中存在的每個對象的number實例變量與accountNumber進行比較。

實施例:

public boolean hasAccountNumber(int accountNumber) { 
for (Account a : getAccounts()) { 
    if (a.number == accountNumber) { 
     return true; 
    } 
} 
return false; 

}

1

因爲原來的陣列組成的對象和代碼正在檢查的對象中的一個的該沒有返回結果等於帳號。這不是一個有效的比較,因爲您應該真正在做的是檢查列表中的每個對象是否有一個等於帳號的號碼。

所以你的算法會,

1. Set current_position = 0; Start iterating through the list; 
2. Extract object at current_position 
3. Does object.number == account_number? true {then break} : false {increment current_position} 
4. Continue until end of array 
2

你會通過Account■找循環和查詢每一個爲它的帳號。

boolean accountsContain(int accountNumber) { 
    for (Account account : getAccounts()) 
    if (account.number == accountNumber) 
     return true; 

    return false; 
} 

(附註:如果它看起來應該有一個更簡單的方法,也完全是,但Java不能做到這一點(還)。看看函數式編程)

1

數組b包含Account對象,而不是數字。所以,你必須手動遍歷數組,並檢查各Account對象數量相匹配:

public boolean hasAccountNumber(int accountNumber) { 
    for (Account account : getAccounts()) { 
     if (account.number == accountNumber) { 
      return true; 
     } 
    } 
    return false; 
} 

說了這麼多,更好的設計很可能會在一個Map賬戶從賬戶到商店Account對象本身。

相關問題