Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java logic issues

Tags:

java

loops

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!

like image 377
shewontreply Avatar asked Nov 23 '25 03:11

shewontreply


1 Answers

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.

like image 75
Sednus Avatar answered Nov 24 '25 19:11

Sednus