Java 如何初始化此特定变量?

Java 如何初始化此特定变量?,java,variables,methods,initialization,boolean,Java,Variables,Methods,Initialization,Boolean,所以我有这个方法: 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

所以我有这个方法:

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返回不同的内容。问题是变量path尚未初始化,我不太确定如何初始化它,因为如果方法findPath为true,我想返回path

您的代码中有一个主要缺陷

path
是一个方法局部变量。因此,除非它作为参数传递,否则不能在其他方法中访问它

因为在您的
findPath
方法中,您没有获取/传递
path
,所以返回path实际上没有什么意义


您可以将
path
初始化为
null
new MazeLocationList()
,但这不会有任何好处,因为
path
没有被更改。

您的变量路径根本没有得到任何值,因此初始化与否无关紧要

如果值从未更改,返回路径的想法是什么

编辑:

如果只想返回
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();
}

MazeLocationList路径;这是否有任何默认值?或者您需要在某个地方进行计算?我尝试返回MazeLocationList的一个实例,但是我不太确定如何执行该操作。请参阅上面的编辑。如果你只想返回一个实例,用MazeLocationList的一个新实例初始化它,或者在If语句中返回它。现在我得到一个编译器错误,它说MazeLocationList是抽象的,不能实例化。程序应该做的是返回MazeLocationList的一个实例,如果findpath方法没有路径,那么它只返回null。我只是对MazeLocationList的返回和实例的含义感到困惑。我看不到MazeLocationList类的实现,但是如果它的抽象意味着它是一个无法实例化的类。我不知道你的整个代码的想法,但是一个抽象类被用来创建一个可以实例化的继承子类。