Stitch
Stitch

Reputation: 31

Java: For loop print statement for two dimensional array

I'm trying to do a two dimensional for loop that with print this:

7 5 3 1

2 4 6 8

Here is my array:

int [][] secondArray = {{7, 5, 3, 1}, {2, 4, 6, 8}};

The for loop below will only print it one number after the other. Not all on one straight line. I have tried playing around with it. Like making two print statements. On for i and j. Or doing a "\t". I'm just learning arrays and this for loop was the closest example I got online.

 for(int i = 0; i < secondArray.length ; i++)
     {

            for(int j = 0; j < secondArray[i].length; j++)
            {

                System.out.println(secondArray[i][j]);

            }

     }

Edit: I guess I should put that I understand how for loops work. It goes through each number and prints it. I guess my question is, how else would I do this?

Upvotes: 0

Views: 543

Answers (3)

SalmaSulthan
SalmaSulthan

Reputation: 61

this also works..

  int [][] secondArray = {{7, 5, 3, 1}, {2, 4, 6, 8}};

     for (int i = 0; i < secondArray.length ; i++)
     {

         for(int j = 0; j < secondArray[i].length; j++)
         {
             System.out.print(secondArray[i][j]);
             System.out.print(' ');

       }

         System.out.println();
     }

Upvotes: 0

H. Sodi
H. Sodi

Reputation: 550

Use System.out.print() instead of System.out.println() if you don't want to the next output to be from next line.

Code

for(int i = 0; i < secondArray.length ; i++) {
    for(int j = 0; j < secondArray[i].length; j++) {
         System.out.print(secondArray[i][j] + " ");
    }
    System.out.println();
}

Upvotes: 1

Washington A. Ramos
Washington A. Ramos

Reputation: 924

Use a foreach loop and print a line everytime you jump from one inner array to another:

for(int[] a : secondArray) {
      for(int b : a) {
        System.out.print(b);
        System.out.print(' ');
      }
      System.out.println();
}

Upvotes: 2

Related Questions