Reputation: 509
public static void main(String[] args) {
String[] Test = new String[]{"1","2","3","4","5","6","7","8","9"};
}
I want to be able to print like this.
1 2 3
4 5 6
7 8 9
I have tried by using for loops three times to print it but i was wondering if there is an easier way to do it.
Upvotes: 0
Views: 108
Reputation: 56714
Try:
for ( int i = 0 ; i < Test.length ; i++ ) {
System.out.print(Test[i]+" ");
if ( i%3 == 2 ) {
System.out.println();
}
}
or
for ( int i = 0 ; i < Test.length-2 ; i++ ) {
System.out.print(Test[i]+" "+Test[i+1]+" "+Test[i+2]+"\n");
}
and change the name for Test
in test
.
Upvotes: 1
Reputation: 1263
public static void main(String[] args) {
String[] Test = new String[]{"1","2","3","4","5","6","7","8","9"};
for(int i = 1; i <= Test.length; i++) {
System.out.print(Test[i - 1]+" ");
if(i % 3 == 0)
System.out.println();
}
}
Upvotes: 1
Reputation: 70949
For perfect alignment, you need to do two passes. One to keep track of the maximum size of each to-be-printed column, and the second to print all the columns adjusted to the desired size.
This is because if you start printing the first line
1 2 3
some devious movement of the universe will eventually guarantee that the second row will contain the numbers
3425 2352342 2
and it will blow your alignment. However, if you walk the data one time, updating the maximum size of the column (if necessary)
(row 1) (column 1 max size is 1) (column 2 max size is 1) (column 3 max size is 1)
(row 2) (column 1 max size is 4) (column 2 max size is 7) (column 3 max size is 1)
then the second time you go through the data, you can print each row with the correct amount of padding (spaces for max column width - width of data, and then the value)
1 2 3
3425 2352342 2
Now as to how to transform a one dimensional array into a two dimensional array, it depends. One could just declare a two dimensional array from the start, or you could specify the width of the row, counting off elements until a row is "filled".
Both techniques will work, and depending on circumstance, you might find that one approach fits some problems better than the other (but there's likely not a perfect solution for all problems).
Upvotes: 0
Reputation: 195229
printf could help.
This loop should do:
for (int i = 0; i < Test.length; i++) {
System.out.printf("%s%s", Test[i], i % 3 == 2 ? "\n" : " ");
}
Upvotes: 2