public static int search(int[] a, int target) { int i=0; boolean found = false; while((i<a.length) && ! found) { if (a[i] == target) { found = true; } else i++; } if (found) return i; else return -1; } I dont understand the if statement part. So how i am reading it in my head is found is set to false. If not found...so if not false (since found = false), do whatever. So basically im reading it as a double negative and seeing if (true) dow whatever. But it doesnt make sense. I know its not an inifite loop and it runs fine but I dont get the logic, it must not be a double negative. Thanks!
EDIT: So i get that we could just return i, much easier yes I agree. I just am having trouble with the logic of the boolean value being used in the loop with the not "!" symbol.
Basically if i wrote this i would say (ignoring everything else)
found = true //found is true to begin with while (!found) //while not true continue to next index //continue until ....actually i'm getting very confused now because to break the loop we would continue until found is false which logically is backwards
EDIT: Thank you everyone for your comments!! It all helped me understand it!
found = true;. Then at the very end always return -1, because you'll only reach it if nothing was found. --- I don't blame you for not getting this, it's written slightly weirdly.foundtofalse, so you are executing the codeblock inside the while loop as long as!found– indeed a double negation (foundwasfalse, sonot falseistrue).whileonly executes as long as the statement inside the parenthesis istrue.