Java : Object access with private fields

标签 java arrays oop

这是我的两个类。 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/

相关文章:

java - 将java文本转换为pdf然后打印

c - 如何创建一个程序,要求用户输入 "up to"20 个整数,并使用传递给函数的参数来输出最大值、最小值和平均值?

python - 切割结构化 numpy 数组

actionscript-3 - 何时子类化以及何时使用现有类?

java - 为什么今天开发Android需要与gradle同步?

C# - 我怎样才能拥有一个引用任何实现一组接口(interface)的对象的类型?

python - Python 中大数据结构的性能

java - 需要澄清 Java 中监听器匿名类的概念

javascript - 对象方法比全局函数快吗?

java - 接口(interface)的实现必须实现其内部类构建器接口(interface)。怎么做?