简体   繁体   中英

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;
  }

}

I am guessing it's the following:

When values[i] is true the line : i = output [z]; will try to reach an index which might be greater than 2 .

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;
  }


  }

Should use something like this, instead:

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

This problem is occurred because the values.length is greater than arrsize . Consider following scenario.
In your input, there are 3 true values and 2 false values. Your code says that arraysize will be increment if values[i] is true. So here arraysize is 3, but values.length is the size of boolean array which contains true and false also which is 5. Your inner loop is running up to values.length ie 5 and your output array's size is 3. That's why ArrayIndexOutOfBoundsException exception occurred.

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

Here output array size will be less than values array size. Hence it throws ArrayIndexOutOfBoundsExecption .

Here is a modified code that works, using ArrayList.

public static void main(String[] args) {

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

    ArrayList<Integer> o = longestStreak(test);
    for(int x : o) System.out.println(x);
}

public static ArrayList<Integer> longestStreak(boolean[] values) {
    ArrayList<Integer> maxStreak = new ArrayList<Integer>();
    int currentStreak = 0;

    for (int x = 0; x < values.length; x++)
        if(values[x]) {
            if (++currentStreak == 1)maxStreak.clear();
            if (currentStreak >= maxStreak.size()) maxStreak.add(x);

        } else currentStreak = 0;

    return maxStreak;

}

Here is the output (positions of the max streak in boolean array)

2
3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM