这是我的两个类。 Eclipse,在 while 循环内的 myGrid[0] 下划线,我收到一条消息“表达式的类型必须是数组类型,但它解析为 Grid”。感谢任何帮助。
public class Grid {
private int[][] myGrid;
private int x, y;
public Grid(int x, int y) {
myGrid = new int[y][x];
}
}
<小时/>
import java.util.Scanner;
public class Play {
private Scanner input = new Scanner(System.in);
private void setPosition (Grid myGrid) {
boolean counter = false;
while (counter == false) {
System.out.println("Give a position, from 0 to " + myGrid[0].length-1 + " : >");
x = Integer.parseInt(input.nextLine());
}
}
}
最佳答案
您将 Grid 类与其 myGrid 字段混淆了。他们是完全不同的。只是因为您为 Grid 参数指定了与其字段相同的名称,所以它不是同一件事。 myGrid 是一个纯粹而简单的 Grid 变量,而不是一个数组。
这里:
private void setPosition (Grid myGrid) {
myGrid 是一个 Grid 变量,不是数组,不能被视为数组。如果这是我的代码,我会给 Grid 类一个 getColumnCount()
方法
public class Grid {
private int[][] myGrid;
private int x, y;
public Grid(int x, int y) {
myGrid = new int[y][x];
}
public int getRowCount() {
return myGrid.length;
}
public int getColumnCount() {
return myGrid[0].length;
}
}
并调用它:
private void setPosition (Grid myGrid) {
boolean counter = false;
while (!counter) {
System.out.println("Give a position, from 0 to " + (myGrid.getColumnCount() - 1) + " : >");
x = Integer.parseInt(input.nextLine());
}
}
关于Java : Object access with private fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36272495/