【问题标题】:Java How do I create a unique object name?Java 如何创建唯一的对象名称?
【发布时间】:2016-04-30 02:58:10
【问题描述】:

每当用户想要创建新帐户时,我将如何创建唯一对象?

例如,如果用户创建了一个帐户,我想要一个名为 acc1 的对象,那么如果用户创建另一个帐户,我想要一个名为 acc2 的对象。 Account ac = new Account(input.nextInt(),0,0);。这就是我需要它发生的地方。

我尝试使代码尽可能简单,并注意我对 java 还很陌生,这是一个个人项目,仅供学习。

 System.out.println("Welcome to JAVA Bank");
    System.out.println("____________________");
    System.out.println("Plese Choose an Option: ");
    System.out.println("");
    System.out.println("(1) New Account");
    System.out.println("(2) Enter Existing Account");



    int choice = input.nextInt();


    switch(choice){

        case 1:
            System.out.println("Please choose an Account ID#");
            Account ac = new Account(input.nextInt(),0,0);
            break;




public class Account {

private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
private Date dateCreated;

public Account(int id, double balance, double annualInterestRate) {
    this.id = id;
    this.balance = balance;
    this.annualInterestRate = annualInterestRate;
    this.dateCreated = new Date();

}

感谢您的帮助。

【问题讨论】:

标签: java class object user-input


【解决方案1】:

如果您想要一种识别多个帐户的独特方法,那么 HashMap 可能是您的最佳选择。 HashMap 存储键值对,其中每个键都是唯一的。

创建一个类级变量来存储帐户:

Map<String, Account> accounts = new HashMap<String, Account>();

创建/添加帐户到 HashMap:

case 1:
    System.out.println("Please choose an Account ID#");
    int accountID = input.nextInt(); //Get the requested ID
    if (accounts.containsKey("acc"+accountID) //Check to see if an account already has this ID (I added acc to the start of each account but it is optional)
    {
       //Tell user the account ID is in use already and then stop
       System.out.println("Account: " + accountID + " already exists!");
       break;
    }

        //Create account and add it to the HashMap using the unique identifier key
        Account ac = new Account(input.nextInt(),0,0);
        accounts.put("acc"+accountID, ac);

【讨论】:

  • 感谢您对 cme​​ts 的清晰简单的回答。我会试一试,看看它是如何实现我想要完成的目标的。所以每次创建一个帐户时,它都会通过 hashmap 收到一个唯一的 ID?如果有多个,我将如何通过该 ID 访问它?还是应该通过我的班级 ID 访问?
  • 您可以通过accounts.get("acc"+ID);访问该账户。请注意,如果帐户不存在,它将返回 null 而不是帐户。
  • 我在哪里插入 Map accounts = new HashMap(); ???我试着把它放在任何地方,但它不起作用。它说找不到符号类:地图。我试着把它放在我的课堂上,不同的方法,在 main 中,我改进了 util.hashMap 并且没有任何效果
  • 我尝试向它添加哈希。我尝试将它插入任何地方。它根本不起作用
  • 你导入的是 util.HashMap 还是 java.util.HashMap?另外,如果你使用 Eclipse,你可以按 ctrl-shift-o 来自动导入类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-21
相关资源
最近更新 更多