-1

The solution was to remove static from my variables in the Account class. The code now works as intended

I am trying to make a method that will check if a number is in an arraylist of objects

My initial thoughts were this but this is not working currently. My main class is this withoutirrelevant code

private static ArrayList<Account> accounts = new ArrayList<Account>();
public static void main(String[] args) 
{       
    //Creates the three default accounts
    Account ac1 = new Account("account1", 0001, 0);
    Account ac2 = new Account("account2", 0002, 0);
    Account ac3 = new Account("account3", 0003, 0);
    accounts.add(ac1);
    accounts.add(ac2);
    accounts.add(ac3);
}
public static void createAccount()
{
    Boolean doesContain = false;
    String logAccNum = JOptionPane.showInputDialog("please enter your account Number");                 
    int tempAccNum = Integer.parseInt(logAccNum);
    doesContain = checkArray(tempAccNum);       
}
public static boolean checkArray(int checkNum)
{
    for(int i = 0; i <accounts.size(); i++)
    {
            if(accounts.get(i).getMyAccountNum() == checkNum)
            {
                return true;
            }   
    }
    return false;
}

My code in my Account class without irrelevant code is

private int myAccountNum;
private int myBalance;
private String myName;

public Account(String name, int accNum, int balance)
{
    this.myName = name;
    this.myAccountNum = accNum;
    this.myBalance = balance;       
}

public int getMyAccountNum()
{
    return myAccountNum;
}

The current issue with my code is that checkArray will only return true if the number entered in createAccount is the last default account created. I believe that the myAccountNum variable in the Account class is staying the same after the last instance of it being constructed.

Lastly, I do not want to use iterators in the solution unless necessary, if you could use arrayList and for loops to create it that'd be greatly appreciated

BobH
  • 1
  • 1
  • See: https://stackoverflow.com/questions/19843506 Also FYI, if you prefix your integer literals with `0`, that actually creates an octal literal. – Jorn Vernee Mar 03 '18 at 22:43
  • https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html – JB Nizet Mar 03 '18 at 22:44

2 Answers2

0

The attributes myAccountNum, myBalance, myName must be NON static, since these mean they exist independent of a class instance. When you instantiate new Accounts, they'll all be referring to the same variables rather than possessing their own.

Your code say "share myAccountNum, myBalance, myName" between ALL the instances. It's not your intend.

Mapsy
  • 4,192
  • 1
  • 37
  • 43
Aubin
  • 14,617
  • 9
  • 61
  • 84
0

The reason is because the variable is static.https://beginnersbook.com/2013/05/static-variable/ all static variables have the same value for all objects of that class

tkc
  • 7
  • 4