Search code examples
javamultidimensional-arrayindexoutofboundsexceptioncharacter-arrays

how to initialize 26 characters inside a 6*5 two dimensional matrix without using and extra special characters


``I am a newbie to Java. All i want to do is to store A to Z inside a 2D array like this

A B C D E

F G H I J

K L M N O

P Q R S T

U V W X Y

Z

String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 char[] alpha = alphabets.toCharArray;
 int k=0;
 char[][] cipher = new char[6][5];
 for(int i= 0;i<6;i++)
     {
       for(int j=0;j<5;j++)
           {
             cipher[i][j] = alpha[k];
             k++;
            }
     } 

But this throws an ArrayIndexOutOfBounds Exception i want the array to fill in 26 and leave the rest of the characters to be nulls. Is it possible ??


Solution

  • You can use a break to exit the loop after filling the last letter.

    String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char[] alpha = alphabets.toCharArray();
    char[][] cipher = new char[6][5];
    outerLoop : for(int i=0 ; i<cipher.length ; i++) {
       for(int j=0 ; j<cipher[0].length ; j++) {
           int k = i*cipher[0].length + j;
           if (k >= alpha.length) break outerLoop;
           cipher[i][j] = alpha[k];
       }
    }
    

    You can also use an array that has not the same number of columns in each row (last row would have only one column).