Reputation: 37
This is the code that i made
class Printsqu {
public static void main(String[] args) {
int[][] array = { { 1,5,9,13 }, { 2,6,10,14 }, { 3,7,11,15 },
{ 4,8,12,16 }, };
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print( array[i][j]);
}
System.out.println();
}
}
}
the output should be
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
this but it prints out
1593
261014
371115
481216
So I added \t between them but it jumps too much.
Is there any way to fix this?
funny thing is that the space between numbers are different
I would grateful if you guys add details about code and explanations thanks.
Upvotes: 1
Views: 546
Reputation: 1510
Replace the value of WIDTH
with whatever number of characters you want to give for one number.
class Printsqu {
public static final int WIDTH = 3;
public static void main(String[] args){
int[][] array = { { 1,5,9,13 }, { 2,6,10,14 }, { 3,7,11,15 },
{ 4,8,12,16 }, };
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.printf("%"+WIDTH+"d", array[i][j]);
}
System.out.println();
}
}
}
Upvotes: 1
Reputation: 620
try this
public static void main(String[] args) {
int[][] array = { { 1,5,9,13 }, { 2,6,10,14 }, { 3,7,11,15 },
{ 4,8,12,16 }, };
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.printf("%2d ", array[i][j]);
}
System.out.println();
}
}
Upvotes: 2