Penny
Penny

Reputation: 3

Confirm Java ArrayList contains a specific value

I have a "bank" program, with the following chunk of code:

private void doPayment(JTextField accountNumField, JTextField paymentField)
    {
        int accountNum = Integer.parseInt(accountNumField.getText());
        double paymentAmt = Double.parseDouble(paymentField.getText());
        String paymentProcessed = "-RECEIPT OF PAYMENT-" + "\n\n" + "Account Number:" + " " + accountObject.getAccountNum() + "Beginning Balance:" + " " + accountObject.getBegBalance() 
        + "Payment Amount:" + " " + accountObject.getPaymentAmount() + "Ending Balance:" + " " + accountObject.getEndBalance();
        String errorMsg = "ERROR: ACCOUNT NUMBER" + " " + "[" + accountObject.getAccountNum() + "]" + " " + "NOT FOUND. PLEASE VERIFY THAT THE ACCOUNT INFORMATION IS VALID AND CORRECT.";

        if (accountsArrayList.contains(accountNum))
        {
            accountObject.transactionTwo(paymentAmt);
            JOptionPane.showMessageDialog(null, paymentProcessed, "PAYMENT PROCESSED SUCCESSFULLY", JOptionPane.PLAIN_MESSAGE);
        }
        else
        {
            JOptionPane.showMessageDialog(null, errorMsg, "INVALID ACCOUNT ERROR", JOptionPane.PLAIN_MESSAGE);          
        }

    }

In theory, after the user creates the account for the client, he/she navigates to a "Process Payment" window and enters two things: accountNum and paymentAmt then hits submit, at which point the doPayment method is called.

This method is supposed to work such that the program iterates through the accountsArrayList which contains THREE items: lastName, firstName, and accountNum. If it finds that the accountNum provided matches a prexisting accountNum in the arrayList, then the transaction is processed accordingly. If no matching accountNum can be found then it returns an error message.

At present, it just returns the error message in the else part of the if-else. I thought that the contains(item) method automatically iterates through the Arraylist. If that isn't the case, do I need an enhanced FOR-loop?

Upvotes: 0

Views: 62

Answers (1)

SputnikHemp
SputnikHemp

Reputation: 61

    if (accountsArrayList.contains(accountNum))

accountsArrayList is a ArrayList which contains Objects of type Account.

contains returns true only if accountsArrayList contains an Object type Account given as argument. In your code, accountNum is a int so the compiler reads it like if(Account == INTEGER)

You have to go throw each Account in your ArrayList and get it's accountNum and than compare the values.

for(int i = 0; i < accountsArrayList.size; i++){
   if(accountsArrayList.get(i).accountNum == accountNum){
     //success
   }
   else {
     //error
   }
}

Upvotes: 1

Related Questions