Reputation: 1
Basically I am trying to create an object and calling it via the main method/ a constructor. When I print it out I get a list but I needed it printed out like a table. Here is the code:
import java.util.Arrays;
public class test2 {
public static String[][] makeTable(int mouseLocationRow, int mouseLocationColumn) {
int rows = 12;
int columns = 12;
String[][] a = new String[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
a[i][j] = "#";
}
}
a[mouseLocationRow][mouseLocationColumn] = "&";
return a;
}
public static void main(String[] args) {
int a = 5;
int b = 5;
System.out.println(Arrays.deepToString(makeTable(a, b)));
}
}
Here is the output:
[[#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, &, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #], [#, #, #, #, #, #, #, #, #, #, #, #]]
Here is how its supposed to look like:
############
############
############
############
############
#####&######
############
############
############
############
############
############
How do I make my output look like how its supposed to look like?
Upvotes: 0
Views: 1394
Reputation: 230
Are you looking for something like :
public void print2DArray(int[][] arr) {
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++) {
System.out.print(" " + arr[row][col]);
}
System.out.println();
}
}
And Call it from your main method like this:
int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
print2DArray(arr);
Or did i miss something ?
Upvotes: 0
Reputation: 2897
You might want to use char[][] instead of String[][]..
Then, to display, use something like printTable() below:
import java.util.Arrays;
public class test2 {
public static char[][] makeTable(int mouseLocationRow, int mouseLocationColumn) {
int rows = 12;
int columns = 12;
char[][] table = new char[rows][columns];
for (char[] row : table)
Arrays.fill(row, '#');
table[mouseLocationRow][mouseLocationColumn] = '&';
return table;
}
public static void printTable(char[][] table) {
for (char[] row : table)
System.out.println(new String(row));
}
public static void main(String[] args) {
int a = 5;
int b = 5;
printTable(makeTable(a, b));
}
}
Upvotes: 1