Problem: Write a method that will check an array for an odd number followed by an even number. Find the first odd number. Then, after finding the odd number, start looking at that position for an even number and then return the distance between them. Return -1 if there are no odd numbers or no odd numbers followed by an even number.
Data: An array containing 0 or more values. The array will not point at null.
Output: Return the distance or -1.
Sample Data:
7, 5, 10, 12
3, 5, 7, 1
2, 4, 3, 8, 10, 12
11
5, 3, 11, 6, 7, 11, 8
Sample Output
2
-1
1
-1
3
Here is the introduction to a problem from apluscompsci.com. This problem is one that was assigned to the students in my AP Computer Science class. So, my code to this problem goes as such:
int go( int[] array )
{
int o = 1;
int e = 0;
int distance = e-o;
if(array.length==0)
{
return distance;
}
for(int a = 0, y = 0; a < array.length || y<1; a++)
{
if(array[a]%2==1)
{
y++;
o = a;
for(int b = a + 1, x = 0; b < array.length || x<1; b++)
{
if(array[b]%2==0)
{
x++;
e = b;
}
}
}
}
if(e==0)
{
o=1;
}
return distance;
}
For some reason, the code that I've constructed to solve the problem keeps firing a "java.lang.ArrayIndexOutOfBoundsException" error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 13
at Submission.go(typed.java:30)
at Submission.main(typed.java:9)
This couldn't be possible, though, as I've coded this solution in the most abstract way possible and my for loops never request an index that doesn't exist. Not even the teacher or the smartest kids in the room could help me find out and I've tweaked this code for almost 3 days. I've tried troubleshooting by reconstructing the code in Eclipse, in the case that this website's JavaScript may not support some of the extra techniques I used such as the multiple variable initiations and the or operators in my for loops, but it spits back the same error.
Also, this is my first question here on this site! I actually just made an account to ask this, lol! Hope I laid everything out plain and simple - thanks in advance for any help!