Reputation: 46
I'm trying to make a two dimensional array and output the results [3][3] in 3 lines and 3 colons, but I get it like 123456789 in a straight line. Now I know that I get this result because of the "println" command but I would like to know how can I get it work the way I want it to. Sorry, I'm new to programming.
import java.util.Scanner;
public class klasa {
public static Scanner lexo = new Scanner(System.in);
public static void main(String[]args){
int[][] array = new int[3][3];
for(int a=0;a<3;a++){
for(int b=0;b<3;b++){
System.out.println("Shkruaj numrat: ");
array[a][b]= lexo.nextInt();
}
}
for(int a =0; a<3;a++){
for(int b=0;b<3;b++){
System.out.println(array[a][b]);
}
}
}
}
Upvotes: 0
Views: 94
Reputation: 18964
for(int a = 0; a<3; a++){
for(int b=0; b<3; b++){
System.out.print(array[a][b]);
System.out.print(" ");
}
System.out.println();
}
(That prints trailing spaces on each line, but it's a decent start.)
Upvotes: 1
Reputation: 40315
Use plain old print for each value, then print a newline after each row in your outer loop.
In general make your code reflect precisely what you are trying to do: Print each element in a row, followed by a newline. The computer generally follows your instructions to the letter.
Upvotes: 0
Reputation: 655
You should try:
for(int a = 0; a < 3;a++){
for(int b = 0; b < 3;b++){
System.out.print(array[a][b] + " ");
}
System.out.println(); //new line
}
to make a new line only after three elements (and add spaces (optional)).
Hope this helps.
Upvotes: 1