0

I'm still learning Java and I was wondering how can I access an element of an array? For example, I have this array:

private int[] employeeNum={5658845, 4520125, 7895122, 8777541, 1302850, 7580489};

And I want to display the number "450125" while using a for loop. What should I do? Also, if you have a better method rather than a for loop, please feel free to put it; it would be much appreciated. I'll put in the for loop I'm using just in case :

for(int i=0; i<6; i++) {
    System.out.println("Enter the hours worked by employee number " +
    employeeNum[i] + ":");
}
8
  • import java.util.Arrays; System.out.println( Arrays.toString(employeeNum) ); Commented Oct 17, 2014 at 17:55
  • 2
    Do you want to display 45202125 or do you want to display the second element in your array? these are two very different questions. Commented Oct 17, 2014 at 17:55
  • 1
    By "access an element of an array", do you mean "find a specific value in an array"? Commented Oct 17, 2014 at 17:55
  • Your accessing array elements in your for loop. employeeNum[i] is getting the element at index i. Commented Oct 17, 2014 at 17:55
  • DwB: display the second element in the array. Commented Oct 17, 2014 at 17:58

1 Answer 1

2

If you would like to display the second element in an array, you simply need to do this: arrayName[indexNumber]
In your case, you would need to use this syntax:
employeeNum[1]

An index (such as "indexNumber" and "1" used above) is simply an address. The former being a variable representing a number, and the latter being a number. Imagine you had ten houses on the right side of a given street. If you were to explain to someone else how to get to the second house on the right, you would say something like this:
houses[1]
Why did I put a '1' instead of a '2'?
Because, in programming, you start counting at '0' instead of '1'.
I hope this helps. Be sure to up-vote those comments that are helpful, and mark the best answer.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the rapid response! This is exactly what I needed!
@Redington You're welcome. Please be sure to up-vote those answers that you find answer to original question well. Not just in questions you have asked, but also in other question threads as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.