[英]Java : Object access with private fields
这是我的两节课。 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变量,不是一个数组,因此不能这样处理。 如果这是我的代码,我getColumnCount()
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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.