C. Miller C. Miller - 3 years ago 39
Java Question

Retrieving a certain array index in an array of objects using a known attribute?

Here is some background for my program:

For class, I'm making a fake log in system.

It uses an array of objects each with attributes assigned.

It seems to have a problem when I try to retrieve the object index for the username/password pair.

I want this index number so I can do more with the user object while they are "logged" in.

However, no matter the username password pair , it has issues getting the correct one.

Here is how I am trying to retrieve it:

static int getIndex(User[] users, int index, String userID, String userPin)
for (int i = 0; i < users.length; ++i)
if (users[i].getUserID().equals(userID) && users[i].getPassword().equals(userPin));
index = i;
return index;


I added in a print statement to see what it was doing.

It prints


and sends the last number, in this case 2, out of the method to be used.
Alternatively, if I tell it to return within the if block, it just sends back 0 regardless of what username I use.

I've also looked around on this site for other solutions, and they all seemed rather similar to what I'm trying to do except some use an array list. I'm not sure where I am going wrong.

I'd like to keep my array of objects as an array of objects if possible or maybe do a quick conversion back and forth if it really needs to be changed.

Ultimately, I'd like to be able to grab the index ( 0, or 1, or 2) depending on whose username and password is entered and return it to be used as the index elsewhere.

Below is the rest of the code, it has a class to use too, but I didn't want to bombard people with code.

import java.util.Scanner;
public static void main(String[] args) {
User[] users = new User[3];
users[0] = new User();
users[1] = new User();
users[2] = new User();




Scanner userInput = new Scanner(System.in);
System.out.println("Enter your user ID");
String userID = userInput.nextLine();
System.out.println("Enter your PIN");
String userPin= userInput.nextLine();
int Index = 0;

Index = getIndex(users, Index, userID, userPin);
System.out.printf("Welcome %s %s\n\n", users[Index].getFirstname(), users[Index].getLastname());

Thanks for the assistance!

Answer Source

I can see there are two mistakes in your code.

  1. in getIndex(...) method you have putted ; (semi column) after if.
  2. you have used "username" instead if "userID" in if condition.

This will solve your problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download