簡體   English   中英

Java:使用私有字段進行對象訪問

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM