So I have to print out an array which:
- The first cell defines the dimension of the square array. So, I have the
input
Scanner
. - On the first row of the array, every cell has to be the triple of the previous one minus one.
- For every next row, every cell has to have the double of the same column of the previous line, plus the number of the column.
- For example: if the input of the dimensions is 4, like
showArrray(creerArray(4));
, then it should print something like:
4 11 32 95 8 23 66 193 16 47 134 389 32 95 270 781
I already coded the part for the input dimension, but I am stuck at trying to figure out how to code this sequence:
public static void showArray() { } public static void createArray() { int square= 0; int[][] int2D = new int[square][square]; java.util.Scanner input = new Scanner(System.in); square= input.nextInt(); System.out.println("Enter the dimension of the array:" + square); int counter=0; for(int i=0; i<square; i++) { for(int j=0; j<square; j++){ int2D[i][j]=counter; counter++; } input.close(); } ****i have to start coding the sequence here }
Answer
It’s all a matter of where you place your calculations within the for
loops to generate the 2D Array, for example:
// Get Array size from User... Scanner userInput = new Scanner(System.in); int aryLength = 0; // To hold the square 2D Array Rows and Columns length. while (aryLength == 0) { System.out.print("Enter 2D Array square size: --> "); String len = userInput.nextLine(); /* Is the supplied value valid... The Regular Expression passed to the String#matches() method will return boolean true is the variable len only contains a string representation of a signed or unsigned integer value. */ if (len.matches("-?\d+")) { // Yes it is: aryLength = Integer.valueOf(len); } else { System.err.println("Invalid numerical value (" + len + ") supplied!"); System.err.println(); } } // Declare and initialize the 2D Array int[][] array = new int[aryLength][aryLength]; int startVal = aryLength; // Used to calculate the first cell of every array Row // Iterate array Rows... for (int i = 0; i < array.length; i++) { // Iterate Columns of each array row... int cellVal = startVal; // Used for the cell values for all columns in each row for (int j = 0; j < aryLength; j++) { array[i][j] = cellVal; cellVal = ((array[i][j] * 3) - 1); // calculate cell value } startVal = startVal * 2; // Calculate first cell value for very row. } // Display the 2D Array System.out.println(); for (int i = 0; i < array.length; i++) { System.out.println(Arrays.toString(array[i]).replaceAll("[\[\]]", "")); }