简体   繁体   English

Java:使用私有字段进行对象访问

[英]Java : Object access with private fields

This are my two classes. 这是我的两节课。 Eclipse, underlines myGrid[0] inside while-loop and I get a message " The type of the expression must be an array type but it resolved to Grid ". Eclipse在while循环内强调myGrid [0]并得到消息“ 表达式的类型必须是数组类型,但已解析为Grid ”。 Appreciate any help. 感谢任何帮助。

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());
    }
  }
}

You're confusing the Grid class with its myGrid field. 您将Grid类与其myGrid字段混淆了。 They are completely different. 他们是完全不同的。 Just because you give your Grid parameter the same name as its field, it's not the same thing. 仅仅因为您给Grid参数指定了与其字段相同的名称,所以就不一样了。 myGrid is a Grid variable pure and simple, and not an array. myGrid是纯净且简单的Grid变量,而不是数组。

Here: 这里:

private void setPosition (Grid myGrid) {

myGrid is a Grid variable and is not an array and cannot be treated as such. myGrid是一个Grid变量,不是一个数组,因此不能这样处理。 If this were my code, I'd give the Grid class a getColumnCount() method 如果这是我的代码,我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;
    }
}

and call it: 并称之为:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM