Finding Array Element Index in Java?

  • Thread starter Thread starter stripes
  • Start date Start date
  • Tags Tags
    Array Index
AI Thread Summary
To find the index of an element in a single-dimensional array in Java, the indexOf method cannot be used directly as it is not applicable to arrays. Instead, a loop must be implemented to iterate through the array and compare each element to the target value. If a match is found, the index can be returned or stored for later use. The confusion often arises from the fact that indexOf is a method for collections like ArrayList, not for arrays. Therefore, understanding the correct approach to search through arrays is essential for resolving compilation errors.
stripes
Messages
262
Reaction score
0

Homework Statement



If I am given a regular, single dimensional array in Java, how do I search for an element in it, and then how do I get the index of that element?

I have been trying:

Code:
int largest;  //some number that has been predetermined in earlier code
int index3 = data.indexOf(largest);

But it keeps giving me errors in compiling. This method doesn't exist or something. I've read online and indexOf is very confusing. Not sure why I can't simply look up the format of it. I always figured it was

Code:
int number = stringName.indexOf(whatyou'researchingfor);

and then I can use 'number' later on as the index at which 'whatyou'researchingfor' showed up.

Homework Equations





The Attempt at a Solution

 
Physics news on Phys.org
Is the data variable your array? If so, you can't directly evaluate it that way (array doesn't have an indexOf method). You need to create a loop and examine the String values in the array one at a time.
 
Last edited:

Similar threads

Replies
4
Views
1K
Replies
3
Views
1K
Replies
21
Views
3K
Replies
2
Views
1K
Replies
5
Views
2K
Back
Top