gpt4 book ai didi

java - 如何获取类的实例?

转载 作者:行者123 更新时间:2023-12-02 00:08:43 24 4
gpt4 key购买 nike

我有以下代码

class driver{
static BankAccount GetAccount(Customer customer, char c) {
BankAccount accSrc = customer.S;
// savings account
if (c =='S') {
accSrc = customer.S;
// loan account
} else if (c =='L') {
accSrc = customer.L;
// checking account
} else if (c =='C') {
accSrc = customer.C;
// auto loan account
} else if (c =='A') {
accSrc = customer.A;
}
return accSrc;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer forrest = new Customer("Forrest Gump", 1, "42 New Street, New York, New York"); // me
Customer random = new Customer("Random Name", 2, "44 New Street, New York, New York"); // imaginary partner
//try{
String input = JOptionPane.showInputDialog("Please enter your transaction information: ");
Scanner s = new Scanner(input);
int id = Integer.parseInt(s.next());
char action = Character.toUpperCase((s.next().charAt(0)));
char accSrc = ' ';
char accDest = ' ';
double amount = 0;

if(action == 'T'){
amount = s.nextDouble();
accSrc = s.next().charAt(0);
accDest = s.next().charAt(0);
}else if(action == 'G' || action == 'I'){
accSrc = s.next().charAt(0);
}else{
//if D,W
amount = s.nextDouble();
accSrc = s.next().charAt(0);
}

//}catch (IOException e){

//}
if(id==1){
return forrest;
}else if(id == 2){
return random;
}
BankAccount src = GetAccount(forrest, accSrc);
System.out.print(src.getOwner().name);
if(action == 'T'){
BankAccount dst = GetAccount(forrest, accDest);
src.transfer(amount, dst);
.

..
}

class Customer{
protected String name;
protected int id;
protected String address;
protected BankAccount C = new BankAccount(id, this, 0);
protected BankAccount S = new BankAccount(id, this, 0);
protected BankAccount A = new BankAccount(id, this, 0);
protected BankAccount L = new BankAccount(id, this, 0);
...
}

目前我正在硬编码 BankAccount src = GetAccount(forrest, accSrc);我怎样才能继续编写代码,以便它返回给定 ID 号的客户实例(例如 1 给定返回 forrest,2 给定返回随机)?

最佳答案

将您的类放入 Map 例如

 Map<Integer, Customer> classMap = new HashMap<Integer, Customer>();
Customer forrest =
new Customer("Forrest Stallings", 1, "42 New Street, New York, New York");
classMap.put(1, forrest );

Customer random =
new Customer("Random Name", 2, "44 New Street, New York, New York");
classMap.put(2, random );

然后只需将您的类(class)设置为:

Customer forrest= classMap.get(1); 
Customer random = classMap.get(2);

关于java - 如何获取类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13316042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com