samedi 16 mars 2019

Creating out of bounds random number row and column for 2d array

I'm trying to put an array of String into an array of 2d char diagonally. I'm having an issue producing the range of my random number so that it would be in the indexes of my 2D array. My code works but sometimes it would break, giving a "java.lang.ArrayIndexOutOfBoundsException: 60".

useWords is an array of String that the user enter and puzzleBoard is a 2d array of 60 rows and 30 columns.

for (int i = 0; i < userWords.length; i++) {
        int r = rand.nextInt(60); 
        int c = rand.nextInt(puzzleBoard[r].length - userWords[i].length());
         for (int j = 0; j < userWords[i].length(); j++) {
                 puzzleBoard[r+j][c+j] = userWords[i].charAt(j); // -j-j = dia right backward || +j+j= dia right forward || -j+j dia forward || +j-j dia backward
         }
      }

This is the output if the code doesn't break.

This is the output *if* the code doesn't break




Aucun commentaire:

Enregistrer un commentaire