I'm trying to print a chess board grid but it's only printing the A file, then just prints out 7 more blank lines.
Here's my code:
public class Board
{
public static void main(String[] args)
{
char rows = 'a';
int col = 0;
String spot;
int[][] grid = new int [8][8];
for(int i = 0; i <= grid.length; i++, rows++)
{
for(; col < grid.length; col++)
{
System.out.print(rows + "" + (col + 1) + " ");
}
System.out.println();
}
}
}
I'm sure it's something obvious, but I can't figure it out. What do I change to print a full chess board grid?
Doing it with enhanced for loop:
for(int[] row : grid){
for(int square : row){
System.out.print(square + " ");
}
System.out.println();
}
You have to reset col variable. Otherwise it won't execute the second for loop because the condition get failed col < grid.length.
public static void main(String[] args)
{
char rows = 'a';
int col = 0;
String spot;
int[][] grid = new int [8][8];
for(int i = 0; i <= grid.length; i++, rows++)
{
for(col=0; col < grid.length; col++)
{
System.out.print(rows + "" + (col + 1) + " ");
}
System.out.println();
}
}
The col
variable should be initialized properly.
For loop condition should be proper.
see the below code:
public class Board
{
public static void main(String[] args)
{
char rows = 'a';
String spot;
int[][] grid = new int [8][8];
for(int i = 0; i < grid.length; i++, rows++)
{
for(int col = 0; col < grid[i].length; col++)
{
System.out.print(rows + "" + (col + 1) + " ");
}
System.out.println();
}
}
}
output of this code is
a1 a2 a3 a4 a5 a6 a7 a8
b1 b2 b3 b4 b5 b6 b7 b8
c1 c2 c3 c4 c5 c6 c7 c8
d1 d2 d3 d4 d5 d6 d7 d8
e1 e2 e3 e4 e5 e6 e7 e8
f1 f2 f3 f4 f5 f6 f7 f8
g1 g2 g3 g4 g5 g6 g7 g8
h1 h2 h3 h4 h5 h6 h7 h8
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.