Reputation: 51
I'm working on a method that finds the first instance of a given value and returns its position. It works for some cases, but if I give it an array of [1,2,3], and set the value to 2, it returns 0, instead of 1. I'm not sure why, either. Here is the code:
int b = 0;
for(int a = 0; a < values.length; a++) {
if (values[a] == find){
b++;
}
}
return b-1;
Thanks in advance!
Upvotes: 2
Views: 72
Reputation: 2113
Its because you are returning b-1. In fact, if you need to find the same instance and return the index, you wont even need the variable b. You could achieve this with something like this:
for( int a = 0; a < values.length; a++) {
if (values[a] == find){
return a;
}
}
return -1 // Notfound
}
Add the return -1
line for when a value is not found, to use as a sentinel value.
Upvotes: 6
Reputation: 6996
Why not return a
itself instead of doing b-1
;
Maybe you can add a break
statement too to stop iterating as you just need the position of first instance
int b=0,result;
for( int a = 0; a<values.length; a++)
{
if (values[a] == find)
{
result=a;
break;
}
}
return result;
Upvotes: 1
Reputation: 3238
Try
for( int a = 0; a<values.length; a++) {
if (values[a] == find){
return a;
}
}
Upvotes: 2