Assassinator100
Assassinator100

Reputation: 1

Finding an index of an array, then finding the value based off that index

I'm trying to increment through my list with the i value, which represents the index of the array, I then need to find the value based off that index.

I've tried assigning the value of what I'm looking for as -2, then incrementing through the list in order to find the index. But im not entirely sure as to how I get the actual value from the index. studentId isn't what I intended to return, but what it said when I tried returning was it must be an integer. Would someone please be able to show me how to successfully get a value from indexing through a list?

public int studentfinder( int list[]  ,  int studentId  )
{ 
    int correct = -2; 
    for (int i = 0;i<array.length;i++)
    {
        if (list[i] == correct)
        {
            return studentId;
        }
        else
        {
            studentId = -1;
            return studentId;
        }
    }
}

This method must return a result of type int

Upvotes: 0

Views: 47

Answers (1)

Ioannis Barakos
Ioannis Barakos

Reputation: 1369

Check the following code

public int studentfinder( int list[]  ,  int studentId  ) {
    for (int i = 0;i<list.length;i++) {
        if (list[i] == studentId) {
            return studentId;
        }
    }
    return -1;
}

The array.length does not compile at your code, as there is no object with array name.

Lets assume that the studentId is an int inside the int list[] array.

You do a for loop untill you find the list[i]==studentId and when found the method returns that studentId.

If the for loop exits without having found the studentId, it returns -1 that indicates that no studentId has been found in the list (also assuming that studentIds are not negative ints).

Upvotes: 3

Related Questions