簡體   English   中英

如何初始化此特定變量? [關閉]

[英]How do I initialize this specific variable? [closed]

所以我有這種方法:

public MazeLocationList solve(){
    boolean solved = true;
    int startrow = x[0][0];
    int startcol = x[0][0];
    MazeLocationList path;
    boolean S = findPath(startrow, startcol, 15, 20);
    if (S == false){
        solved = false;
        return null;
    } else {
        return path;
    }
}

我正在嘗試做的是嘗試檢查findPath方法返回的是true還是false,然后根據是true還是false返回不同​​的內容。 問題是變量路徑尚未初始化,我不太確定如何初始化它,因為如果findPath方法為true,我想返回路徑。

您的代碼中存在一個重大缺陷。

path是方法的局部變量。 因此,除非將其作為參數傳遞,否則無法用其他方法對其進行訪問。

由於在您的findPath方法中,您不需要獲取/傳遞path ,因此返回路徑實際上沒有任何意義。

您可以將path初始化為nullnew MazeLocationList()但是由於沒有更改path因此它沒有任何new MazeLocationList()

您的變量路徑根本不會獲得任何值,因此是否已初始化都沒有關系。

如果值從未更改,返回路徑的想法是什么?

編輯:

如果您只想返回MazeLocationList的實例,請執行

MazeLocationList path = new MazeLocationList();

或代替返回路徑,返回一個實例:

return new MazeLocationList();

像那樣:

public MazeLocationList solve(){
    boolean solved = true;
    int startrow = x[0][0];
    int startcol = x[0][0];

    boolean foundPath = findPath(startrow, startcol, 15, 20);

    if (!foundPath){
        solved = false;
        return null;
    }

    return new MazeLocationList();
}

暫無
暫無

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

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