Hi Im new to java and I would like to create a grid using java
I want my output to look like this
1 2
3 4
How can I do it with just the toStrings method? I am thinking of using a constructor where if I put (int 2) then it will give me this grid, and if it is (int 3) then it will look like:
1 2 3
4 5 6
CodePudding user response:
You need to use nested for loops. Your method need to take 3 parameters for the row count and column count and also a start number (if say you want to start from 10 instead of 1)
private static String generateGrid(int rows, int cols, int start){
StringBuilder gridBuilder = new StringBuilder();
int nextNumber = start;
for(int row = 0 ; row < rows; row ){
for(int col = 0 ; col < cols; col ){
gridBuilder.append(nextNumber);
gridBuilder.append(" ");
nextNumber ;
}
gridBuilder.append("\n");
}
return gridBuilder.toString();
}
The method returns a String. You are free to print the result or use it for other purposes
CodePudding user response:
Since an answer was already provided, I will post mine:
public static void main(String[] args) throws Exception {
int[][] matrix = {{1,2,3}, {4,5,6}, {7,8,9}};
printGrid(matrix);
}
public static void printGrid(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value " ");
}
System.out.println();
}
}
If you are really concerned about the extra space next to the value, add a string buffer and trim it out before displaying:
public static void printGrid(int[][] matrix) {
for (int[] row : matrix) {
StringBuilder buffer = new StringBuilder();
for (int value : row) {
buffer.append(value " ");
}
System.out.println(buffer.toString().trim());
}
}
By the way, the output of this program is
1 2 3
4 5 6
7 8 9