Eduardo Iannicelli
Eduardo Iannicelli

Reputation: 3

Converting an Object into an Int

Im a begginer in Java and I was wondering how can I do the following process. I would like to automatize the creation of bank accounts (for the sake of learning only). After the creation of those accounts, I want to automatically add them into an array. The catch is that all of those accounts are goint go have a number as their name. The problem is that I'm trying to do that using If's:

int i = 0;
if(i < 10) {
   Account i = new Account();
   list.add(i);
   i++
}

As you can see, I can't use i++, because I can't convert an int into Object.

My goal is to have 10 accounts, all of them added into an Array, and each account would have a number for its name. If I acess the position [3], I would receive and Account named 2. Sorry if it is a little confusing, but I'm trying my best to explain it.

Any help would be fantastic! =D

Thanks!

Upvotes: 0

Views: 53

Answers (2)

Shrirang Kadale
Shrirang Kadale

Reputation: 498

Below is my solution in which I have Account class with one constructor and overridden toString method

import java.util.ArrayList;
import java.util.List;

public class AccountCreation {

    public static void main(String[] args) {
        int i = 0;
        List<Account> accountList = new ArrayList<>();
        while(i < 10) {
           Account account = new Account(i);
           accountList.add(account);
           i++;
        }

        System.out.println(accountList.get(3));
    }  
}

Account class should be something like this

    public class Account {
        int name;

        public Account(int name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "" + name;
        }
}

I hope it will help Thanks...

Upvotes: 0

Villat
Villat

Reputation: 1475

I think that you're mixing up concepts, you could have an Account class with a name property, and do this:

List<Account> accounts = new ArrayList<>();
for(int i=0; i<10; i++){
    Account account = new Account();
    account.setName(String.valueOf(i));
    accounts.add(account);
}

Your class should be something like

public class Account {

    private String name;

    public void getName(){
        this.name = name;
    }

    public void setName(String name){
        return name;
    }
}

Upvotes: 1

Related Questions