Rob Chandramukhi Rob Chandramukhi - 2 years ago 186
Java Question

Array Index out of bounds Java program

Can someone please explain to me why I'm getting an array out of bounds error?

longestStreak : array of booleans -> integer

Purpose: computes the length of a longest streak of consecutive true occurrences in the input argument values

Input : values is a non-null array of booleans with length at least 1

output : outputs the maximal number of consecutive trues found in the input array

import java.util.Arrays;

public class Problem3 {

public static void main (String[] args) {
boolean[] test = new boolean[] {true, false, true, true, false};
int[] o = longestStreak(test);
System.out.println(o);
}

public static int[] longestStreak(boolean[] values) {
int streak = 0;
int max = 0;
int arrsize = 0;
for (int i = 0; i < values.length; i++) {
if (values[i]) {
streak++;
max = streak;
arrsize++;
}
else {
streak = 0;
}
}

int[] output = new int[arrsize];

for (int i = 0; i < values.length; i++) {
for (int z = 1; z < values.length; z++) {
if (values[i]) {
i = output[z];
}
}
}
return output;
}

}

Answer Source

I think the problematic line of code is

i = output[z];

The reason is because I think that you could be setting i equal to a value that is greater than values.length Ok, so I reread your problem statement. This code below will fix it for you and it works. just plug it in: import java.util.Arrays;

  public class Test {


  public static void main (String []args) { 


 boolean[] test = new boolean[] {true, false, true, true, false};

 int[] o = longestStreak(test);
 System.out.println ("{"+o[0] + ", " + o[1]+"}");
  }



    public static int[] longestStreak(boolean[] values) {


 int  streak = 0; 
 int max =0;
 int arrsize =0;
 int maxStart = 0;
 int[] r = new int[2];


 for (int i=0; i<values.length; i++) {
   if (values[i]) {   
     streak++;
//     max =streak;
//     arrsize++;
     }

else {
    if (streak > max) {
        max = streak;
        maxStart = 0;
        maxStart = i - streak;
    }
    streak = 0;
   }
 }
 r[0] = max;
 r[1] = maxStart;
 return r;
  }


  }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download