0

I have this class and it displays the value of arrays after preferred input:

class MyArrayList {

private int [] myArray;
private int size;

public MyArrayList (int value, int seed, int inc){

    myArray = new int [value];
    size = value;
    for (int i = 0; i < size; i++) {
        myArray [i] = seed;
        seed += inc;        
    }       
}   

}

public class JavaApp1 {

    public static void main(String[] args) {
        MyArrayList a = new MyArrayList(5, 2, 1);
        a.printList();

}
}

this program displays an output of: 2 3 4 5 6 now I want to find the index of 4 so that would be 2 but how can I put it into program?

wattostudios
  • 8,666
  • 13
  • 43
  • 57

3 Answers3

2

Loop for the value, then you have the index, you might want this as a function of the MyArrayList class

    int[] myArray = {2,3,4,5,6};
    for (int i = 0; i < myArray.length; i++) 
    {
        if( myArray[i] == 4 )
            System.out.println( "index=" + i);
    }
Orn Kristjansson
  • 3,435
  • 4
  • 26
  • 40
  • +1 since this answer will print **all** occurrences of the queried item. The OP was ambiguous as to what is expected, but this approach seems smarter. – The111 Dec 06 '12 at 01:41
  • Thank you very much sir, although this code doesn't actually work at least I got an idea on how to do it. – Da De Di Dhodong Dec 06 '12 at 14:06
1

You'll need to write a method in your MyArrayList class that takes the value that you're looking for, and locates it in the array. To find it, just loop over the array until the value matches.

Something like this...

public int findIndexOf(int value){
    for (int i=0; i<size; i++) {
        if (myArray[i] == value){
            return i;
        }
    }    
    return -1; // not found   
}   

Now you need to call this new method in your JavaApp1 class and it should return the index.

wattostudios
  • 8,666
  • 13
  • 43
  • 57
  • You also may want to keep in mind that this is not necessarily a unique property. – jonmorgan Dec 06 '12 at 01:40
  • Hmm, yes that could cause a problem, but the OP will need to clarify how he wishes to handle this situation. Currently it will return the first matching index. – wattostudios Dec 06 '12 at 01:41
1

One of the best parts about Java is that it is open source and you can look at the source of all the standard APIs.

This is how the ArrayList.indexOf(Object) method works:

/**
 * Returns the index of the first occurrence of the specified element
 * in this list, or -1 if this list does not contain the element.
 * More formally, returns the lowest index <tt>i</tt> such that
 * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
 * or -1 if there is no such index.
 */
public int indexOf(Object o) {
if (o == null) {
    for (int i = 0; i < size; i++)
    if (elementData[i]==null)
        return i;
} else {
    for (int i = 0; i < size; i++)
    if (o.equals(elementData[i]))
        return i;
}
return -1;
}
Justin Wiseman
  • 780
  • 1
  • 8
  • 27