java - How can I fix my program so that it can work with any number of rows and column user asks? -
import java.util.scanner; public class hi { public static void main(string[] args) { // test //int[][] testarray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int[][] testarray = { { randomnumber(), randomnumber(), randomnumber() }, { randomnumber(), randomnumber(), randomnumber() }, { randomnumber(), randomnumber(), randomnumber() } }; // // display array printarray(testarray); } // end main // display tables private static void printarray(int[][] array) { scanner sc = new scanner(system.in); //ask user system.out.println("how many rows: "); int rows= sc.nextint(); system.out.println("how many columns: "); int columns= sc.nextint(); (int row = 0; row < array.length; rows++) { (int col = 0; col < array[rows].length; col++) { system.out.print(array[rows][columns] + " "); } system.out.println(); } } private static int randomnumber() { int random = (int) (math.random() * 9); return random; } }
currently program working 3 rows , 3 columns. how can make work works rows , columns user inserts?. , methods work whatever user insert?
to use user inputted size, can same thing you're doing in printarray()
, use sizes create array:
public static void main(string[] args) { scanner sc = new scanner(system.in); // ask array size user system.out.println("how many rows: "); int rows= sc.nextint(); system.out.println("how many columns: "); int columns= sc.nextint(); // fill array random numbers int[][] testarray = new int[rows][columns]; (int i=0; i<testarray.length; ++i) { (int j=0; j<testarray[i].length; ++j) { testarray[i][j] = randomnumber(); } } // display array printarray(testarray); } // end main
also, you're using array length instead of current element when walking it:
this looks incorrect
(int row = 0; row < array.length; rows++) { (int col = 0; col < array[rows].length; col++) { system.out.print(array[rows][columns] + " "); } system.out.println(); }
fix (note how rows
, columns
replaced in outer for
, in print()
):
(int row = 0; row < columns; row++) { (int col = 0; col < rows; col++) { system.out.print(array[row][col] + " "); } system.out.println(); }
Comments
Post a Comment