Advertisement
Guest User

Array Filler

a guest
Feb 27th, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.30 KB | None | 0 0
  1.  
  2. import java.util.Arrays;
  3.  
  4. public class ArrayFiller {
  5.  
  6.     /**
  7.      * This will fill a 2D array of any size with letters a-z
  8.      * looping until it reaches the end of the array.
  9.      *
  10.      * @param arrayToFill the array that is going to be
  11.      * filled with characters a-z
  12.      */
  13.     public void fillArray(char[][] arrayToFill) {
  14.        
  15.         //The array of characters with the letters to fill the array
  16.         char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
  17.        
  18.         //Counter to keep track of the index of the alphabet array
  19.         int index = 0;
  20.        
  21.         //Loops through all the empty spaces in the array and fills them
  22.         for(int row =  0 ; row < arrayToFill.length; row++) {
  23.             for(int col = 0; col < arrayToFill[0].length; col++) {
  24.                
  25.                 //Reset the index if it's at the end of alphabet
  26.                 if(index == 26)
  27.                     index = 0;
  28.                
  29.                 //Set the index in the array to fill to a letter at index
  30.                 arrayToFill[row][col] = alphabet[index];
  31.                
  32.                 //increment index
  33.                 index++;
  34.             }
  35.         }
  36.        
  37.        
  38.         //Print the array
  39.         for(int row =  0 ; row < arrayToFill.length; row++) {
  40.             for(int col = 0; col < arrayToFill[0].length; col++) {
  41.                 //Print the element at row, col with a comma
  42.                 System.out.print(arrayToFill[row][col] + ", ");
  43.             }
  44.             //Skips a line when the row is done
  45.             System.out.println();
  46.         }
  47.     }
  48.    
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement