簡體   English   中英

無法更正我的Java程序

[英]Can't correct my java program

我剛開始學習Java,正在研究程序。 我在這里遇到錯誤:

locationsOfCells = simpleDotCom.getLocationCells();

但我不確定是什么錯誤。 Eclipse說

無法從類型simpleDotCom靜態引用非靜態方法getLocationCells()

有人可以幫我弄這個嗎? 我究竟做錯了什么?

public class simpleDotCom {
    int[] locationsCells;

    void setLocationCells(int[] loc){
        //Setting the array
        locationsCells = new int[3];
        locationsCells[0]= 3;
        locationsCells[1]= 4;
        locationsCells[2]= 5;
    }

    public int[] getLocationCells(){

        return locationsCells;

    }
}

public class simpleDotComGame {

    public static void main(String[] args) {
        printBoard();
    }

    private static void printBoard(){
        simpleDotCom theBoard = new simpleDotCom();
        int[] locationsOfCells; 
        locationsOfCells = new int[3];
        locationsOfCells = theBoard.getLocationCells();

        for(int i = 0; i<3; i++){
            System.out.println(locationsOfCells[i]);
        }

    }

}

問題是您實際上在調用getLocationCells()方法,就像它是一個靜態方法一樣,而實際上它是一個實例方法。

您需要首先從您的類中創建一個對象,如下所示:

simpleDotCom myObject = new simpleDotCom();

然后在其上調用方法:

locationsOfCells  = myObject.getLocationCells();

順便說一句,在Java世界中,有一個廣泛遵循的命名約定,其中類名始終以大寫字母開頭-您應將類重命名為SimpleDotCom以避免混淆。

您正在以靜態方式嘗試getLocationCells 您需要首先創建simpleDotCom的實例:

simpleDotCom mySimpleDotCom = new simpleDotCom();       
locationsOfCells = mySimpleDotCom.getLocationCells();

BTW類別名稱始終以大寫字母開頭。 這將有助於消除將方法作為成員方法訪問的困惑。

更新:

要從更新后的靜態方法訪問,還需要將theBoard聲明為static變量:

static simpleDotCom theBoard = new simpleDotCom();

您正在嘗試從main方法引用非靜態方法。 在Java中是不允許的。 您可以嘗試將simpleDotCom類設為靜態,以便您可以訪問該類的方法。

simpleDotCom obj = new simpleDotCom();
locationsOfCells = obj.getLocationCells();

而且您的班級名稱也應該以大寫字母開頭

您正在嘗試從靜態上下文訪問普通的非靜態方法,該方法不起作用。

您可以從嘗試訪問getLocationCells()的例程中刪除該靜態詞,也可以通過在其聲明中添加靜態詞來使getLocationCells()成為靜態。

也可以使simpleDotCom的字段和方法靜態化,或者創建simpleDotCom的實例並訪問該實例的方法。

您的代碼還有更多錯誤。

  1. 非靜態方法無法使用類名調用。 因此,請嘗試使用對象調用getLocationCells()。

    simpleDotCom obj = new simpleDotCom(); obj.getLocationCells()

  2. 接下來,您將獲得空指針異常。 U嘗試在初始化之前打印locationsOfCells值。 因此,嘗試在打印值之前調用setLocationCells()方法。

  3. Ur方法定義void setLocationCells(int [] loc)。 在這里,您具有參數loc,但是您在方法塊中未使用任何位置。 因此請注意處理方法參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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