简体   繁体   中英

Printing integers with for loops

I'm having a strange issue trying to print a 9x9 grid of integers. When I try this code in the main method:

for (int row = 0; row < 9; row++) {         
    for (int col = 0; col < 0; col++) {
        System.out.format( "%d ", entries[row][col] );
        }
    System.out.print("\n");     
}

The output is just a bunch of spaces and newlines, without the actual integers. I've tested 'entries' to make sure it actually contains the correct values (and it does). The weird thing is, when I try the following code also in the main method:

System.out.format("%d ", entries[0][0]);

It works. For some reason the for loop is messing up the output. Any ideas?

You did a mistake in the inner for loop:

for (int col = 0; col < 0; col++)

This wont do any iteration because zero is equals zero.

I think this is what you want:

for (int col = 0; col < 9; col++)

Problem is with the condition in second for loop

for (int col = 0; col < 0; col++) {

It is always false and hence never gets executed.

You should instead use:

for (int col = 0; col < 9; col++) {

This condition is never met:

 for (int col = 0; col < 0; col++) {

so you can just simplify it by doing:

for (int row = 0; row < 9; row++) {         
     System.out.format( "%d ", entries[row][0] );
     System.out.print("\n");     
}

To print a two-dimensional array , you have to print each element in the array using a loop like the following:

 int[][] matrix = new int[9][9];//9*9 grid container

for(int row=0 ; row < matrix.length ;row++){ 
  for(int column= 0 ; column < matrix[row].length;column++){
    System.out.print(matrix[row][column] + "");
   }
  System.out.println();
 }

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