Java 使用字符串变量访问类中的对象
我对JAVA相当陌生,但我正在开发一个程序,这就是我遇到的问题,可能是一个简单的解决方案 我提示用户输入模拟ATM系统的IDJava 使用字符串变量访问类中的对象,java,Java,我对JAVA相当陌生,但我正在开发一个程序,这就是我遇到的问题,可能是一个简单的解决方案 我提示用户输入模拟ATM系统的ID { System.out.println("Enter an ID: "); Scanner input = new Scanner(System.in); String acctID = input.next(); withdrawAccount(ac
{
System.out.println("Enter an ID: ");
Scanner input = new Scanner(System.in);
String acctID = input.next();
withdrawAccount(acctID);
System.out.println(IDnum.getBalance());
}
代码中还有更多内容,但目前与此无关。将有几个if语句来查看用户想要执行的操作,即从他们的帐户中取款。在这个程序中,我想让用户输入ID并将其保存为字符串,然后将其传递给Account方法。因此acctID将引用用户输入的帐户ID。请注意,帐户ID与帐户变量的名称相同。因此帐户0的ID将为0
public static void withdrawAccount(String acctID)
{
System.out.println("Enter Withdraw Amount: ");
Scanner input = new Scanner(System.in);
double WithdrawAmount = input.nextDouble();
acctID.setBalance(acctID.getBalance() - WithdrawAmount);
}
如果我正确理解了您的问题,您希望将字符串ID与这些ID标识的帐户相关联。一种方法是使用地图:
private Map<String, Account> accountsById = new HashMap<String, Account>();
...
accountsById.put("1", account1);
accountsById.put("2", account2);
accountsById.put("3", account3);
...
可能最好将它们存储到ArrayList或Map中
当你调用draw方法时,你需要传递整个“Account”而不是字符串,这样你就可以使用类的“setBalance”方法准确编辑他们的余额。@dnault我想让用户输入ID并将其保存为字符串并传递给drawAccount方法。你应该传递
Account
(或您拥有的类)对象,其中帐户id是用户键入的字符串。这看起来更像是一个设计问题。我希望用户输入id并将其发送到每个方法,因此如果用户输入43,字符串id=输入。下一步();现在我想使用字符串“id”访问已存储在Account对象下的帐户43。
Account account = accountsById.get(idEnteredByTheUser);