Khushboo Ara Khushboo Ara - 4 months ago 9
Java Question

Two Dimensional Array not printing values in matrix format

I am trying to work on some 2 dimensional array examples. While I was trying to print the 2 dimensional array output in the following format

0 1 2

3 4 5

6 7 8

9 10 11

12 13 14


My output was showing up as like this

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14


Not exactly sure what's seems to be the problem

Here is my code:

public class TwoDArray {

public static void main(String[] args) {
int rows = 5;
int columns = 3;
int k = 0;
int[][] array = new int[rows][columns];
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++) {
array[i][j] = k;
k++;
}

for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.println(array[i][j] + " ");
}
System.out.println();
}
}
}

Answer

You have used :

System.out.println(number)

This will create a new line at the end of each number printed. To see output as you want it, you should use :

System.out.print(number)

CODE:

public class TwoDArray {
    public static void main(String[] args) {
        int rows = 5;
        int columns = 3;
        int k = 0;
        int[][] array = new int[rows][columns];
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < columns; j++) {
                array[i][j] = k;
                k++;
            }
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }
    }
}
Comments