Following is the code snippet to print the series:-
111
211
311
121
221
321
131
231
331
112
212
312
122
222
322
132
232
332
113
213
313
123
223
323
133
233
333

But there's some mistake in the code and it gives ArrayIndexOutOfBoundsException.I'm not able to make it out. Please help me out and give me the corrected.

import java.io.*; import java.util.*;
class combine
{ static int[] arr=new int[3]; static int c=0;
public static void initialize()
{
    for(int i=0; i<3; i++ ) arr[i]=1;
}
public static void print()
    {
        for(int i=0; i<3; i++) S.O.P(arr[i]+" ");
        S.O.Pln();
    }
    public static void recursion()
    {
        for(int i=1; i<=3; i++)
        {    arr[0]=i; print();
             if(i==3)
             condition();
             c++;
        }
        if(c<27) recursion();
    }
    public static void condition()
    {   String temp=Arrays.toString(arr).replace(",",""); 
        String str=temp.substring(1,temp.length()-1);
        int n=str.lastIndexOf("3");
        boolean check=false;
        for(int i=0; i<=n;i++)
        for(int j=0; j<=n; j++)
        {  if(arr[i]==arr[j])
            check=true;
                else check=false;}
 if(check) { arr[n+1]++; for(int x=0; x<=n; x++) arr[x]=1;
 }
}
    public static void main(String args[]) throws IOException
    {     initialize();
        recursion();
    }
}

Edited 4 Years Ago by Ravish.Ahmad.Khan

The ArrayIndexOutOfBoundsException meesage includes the line number where it happened, and the index value. Both these are critical info for finding the bug.

also: that's an awfull lot of code, for something such simple. never look for the most difficult solution there can be found. it's usually harder to debug when compared to debugging easy code.

You have declared an array of a certain size, but your program is trying to access part of it outside the limit.

This question has already been answered. Start a new discussion instead.