0

Im trying to make a small CRUD using a ArrayList in Java using the console, when i register a new Account it overwrite the last object and always stay with one object in ArrayList, the List doesn't grow up!

I want to understand my mistake!

My logic:

  • I create a new object of Account in the Main Class;
  • Get the information using the Scanner Class;
  • Send object to method "registerAccount", that will add on an ArrayList;
  • When i print using the getAll() method it display the last object that i register.

My Code:

This class get the information and send to Account class to make the regsiter!

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //Class statements
        Scanner scan = new Scanner(System.in);
        Account account = new Account();

        //Variables statements
        int option = 0;


        System.out.println("---Welcome to Dream Bank-----\n");

        while(option != 4){

            System.out.println("1 - Access your account");
            System.out.println("2 - Create an account");
            System.out.println("3 - List all accounts");
            System.out.println("4 - Exit");

            option = scan.nextInt();

            if (option == 1){

                System.out.println("Comming soon");

            } else if (option == 2){

                System.out.print("Number account: ");
                account.number = scan.nextInt();
                System.out.print("Name: ");
                account.name = scan.next();
                System.out.print("Balance: ");
                account.balance = scan.nextDouble();
                account.special = false;
                account.bound = 1000;

                account.registerAccount(account);


            } else if (option == 3){

                account.getAll();   

            }

        }

        scan.close();   
    }

}

This class contains the method to resgiter and display on console.

public class Account {

    int number;
    String name;
    double balance;
    boolean special;
    double bound;

    List<Account> accounts = new ArrayList<Account>();

    public void registerAccount(Account account){

        accounts.add(account);

    }

    public void getAll(){   

        for(int i=0; i<accounts.size(); i++){
            System.out.println(accounts.get(i).name);
        }

    }

}
Gabriel Gomes
  • 139
  • 1
  • 3
  • 20

0 Answers0