简体   繁体   中英

how to print 3x3 2d array from numbers 1-9 without declaring and initializing vectors In Java?

I have my java solution for printing out numbers 1-9 in a 3x3 matrix below:

     // declare and initialize a 3x3 matrix
    int matrix[][] = 
    { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
  
  // display matrix using for loops
  // outer loop for row
  for(int row =-0; row <matrix.length; row++) {
    // inner loop for column
    for(int column=0; column <matrix[row].length; column++) {
      System.out.print(matrix[row][column] + " ");
    }
    System.out.println(); // new line
  }

So I declared and Intialized a 3*3 vector (Array or matrix) in the code above.

But I want to do print out 3x3 2d array from numbers 1-9 without declaring and initializing vectors.

How do I approach this problem?

Unless I'm missing something, you could use a loop from 1 to 9 and print a newline every third term by testing if the number is divisible by 3 (eg modulo 3 is 0 ). Like,

for (int i = 1; i < 10; i++) {
    System.out.printf("%d ", i);
    if (i % 3 == 0) {
        System.out.println();
    }
}

No arrays (or vectors) required.

Or, you could just print the values instead.

System.out.println("1 2 3");
System.out.println("4 5 6");
System.out.println("7 8 9");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM