[英]How to assign multiple data types to a single variable in java?
現在我正在創建一個銀行應用程序,我不知道如何分配例如字符串名稱; 雙重平衡; 等到右邊一個int PIN;。 將會有許多具有不同 PIN 和分配給它的值的帳戶。 我嘗試制作許多對象:
perInfo card1 = new perInfo();
card1.PIN = 1994;
card1.balance = 24.68;
card1.isValid = true;
perInfo karta2 = new perInfo();
card2.PIN = 2002;
card2.balance = 522.2;
card2.isValid = false;
但我認為要做的工作太多,而且會降低應用程序的性能。 我也試過列個清單
public bApp(int pin, double balance){
this.pin = pin;
this.balance = balance;}
List<bApp> pass = new ArrayList<>();
pass.add(new bApp(1994, 568.45));
pass.add(new bApp(2002, 13866.24));
但它沒有用,因為我無法調用 PIN 來檢查用戶是否提供了正確的 PIN。 數組也不適合這個。
您正在尋找的數據結構是 Map。 看一看 HashMap,您將希望關閉用於查找的任何值。
例如,如果您想通過 pin 查找用戶:
Map<Integer, bApp> passes = new HashMap<>();
passes.put(1994, new bApp(1994, 568.45));
passes.put(2002, new bApp(2002, 13866.24));
您可以為此使用 HashMap 並使用 pin 作為鍵並將對象存儲在 HashMap 中。 這將允許您僅使用 pin 訪問每張卡。 但是,這不允許重復引腳。 我建議您通過唯一 ID 引用每個帳戶,並檢查對象本身內的引腳。
HashMap<Integer, Account> accounts = new HashMap<Integer, Account>();
accounts.put(12345678, new Account(1994, 568.4));
然后,您可以使用唯一 ID 獲取帳戶並檢查 PIN 碼是否正確。
Account acc = accounts.get(uniqueID);
if(acc.pin == enteredPin){
//Whatever you need to do
}
我認為只擁有一個不同卡的數組會更簡單,每個引腳都設置為數組地址:
bApp[] cards = new bApp[NUMBER_OF_CARDS];
cards[0] = new bApp(0, 568.45);
// ...
cards[2002] = new bApp(2002, 13866.24);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.