I'd like to take a second to introduce myself (on top of the question of course); my name's Elvin and I'm an I.T. student at Florida International University. At the moment I am going through some issues learning java and would like someone's assistance in completing the problem. I already know the answer to the problem but that's not what I'm looking for, I want to understand why my code doesn't work as opposed to the code that I found online. Provided is a link to the problem so that you may all see it (basically, in an array, if there is a 2, directly next to another 2 [in the elements of the array] return true, else return false. Seems simple enough right? WRONG! Below is my code and below that is the code that works.
Someone please cure this ache of mine.... thanks in advance for all replies!
Joined: Mar 07, 2013
I seem to have forgotten to provide the link, here it is.
Please UseCodeTags (← click) when posting code as it makes it easier for people to read your code. I've added them for you this time.
Joined: Aug 07, 2007
The difference between the 2 blocks of code is where the "return false;" line is. In your code it's inside the for loop so at the end of the first loop iteration it if it hasn't found a 2,2 the code returns false.
BTW in your code, once you fix the above problem, you will get an IndexOutOfBoundsException if the array doesn't contain consecutive 2's. You need to loop until i < array length - 1.
In future when faced with this type of problem add a print statement in the loop so you can see what is happening.
But let me guess... you get an IndexOutOfBoundsException, right? This indicates that you're trying to access an array element that doesn't exist. Check your code and identify which array index would be invalid at some point.
Edit: ah...I didn't notice the incorrect placement of the return statement that Tony pointed out.