3 回答
TA贡献1789条经验 获得超10个赞
For 循环本身不能在一个类中。类只是声明的地方,而不是代码的地方。Java 中的代码仅在方法中。
所以你有2个解决方案。要么将您的代码放在main方法中:
import java.util.Arrays;
public class BattleshipGrid {
private static char[][] arr1 = new char[10][10]; // Made it static so that
// it would be bound to the class object itself, so that you can see
// it from the main method which is also static and bound to the class
// object
private static char[][] arr2 = new char[10][10];
private static char[][] arr3 = new char[10][10];
private static char[][] arr4 = new char[10][10];
public static void main (String[] args) {
for (char[] i: arr2) {
for(char j: i) {
i[j]='X';
}
}
}
}
另一个(更好)的解决方案是在 main 方法中创建一个类的实例。
import java.util.Arrays;
public class BattleshipGrid {
private char[][] arr1 = new char[10][10];
private char[][] arr2 = new char[10][10];
private char[][] arr3 = new char[10][10];
private char[][] arr4 = new char[10][10];
public void initializeTheGrid() {
for (char[] i: arr2) {
for(char j: i) {
i[j]='X';
}
}
}
public static void main (String[] args) {
BattleshipGrid grid = new BattleshipGrid();
grid.initializeTheGrid();
}
}
TA贡献1757条经验 获得超7个赞
尝试这样的事情:
public class BattleshipGrid
{
private char[][] arr1 = new char[10][10];
private char[][] arr2 = new char[10][10];
private char[][] arr3 = new char[10][10];
private char[][] arr4 = new char[10][10];
public static void main ( String[] args )
{
for ( char[] i: arr2)
{
for ( char j: i)
{
j = 'X';
}
}
}
}
添加回答
举报