【问题标题】:How do I initialize this specific variable? [closed]如何初始化这个特定的变量? [关闭]
【发布时间】:2015-05-05 01:31:33
【问题描述】:

所以我有这个方法:

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 为真,我想返回路径。

【问题讨论】:

  • 迷宫位置列表路径;这有任何默认值吗?或者你需要在某个地方计算?

标签: java variables methods initialization boolean


【解决方案1】:

您的代码存在重大缺陷。

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

由于在您的findPath 方法中,您没有获取/传递path,因此返回路径实际上没有什么意义。

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

【讨论】:

    【解决方案2】:

    你的变量路径根本没有得到任何值,所以不管它是否被初始化。

    如果值从不改变,返回路径是什么意思?

    编辑:

    如果您只想返回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 的新实例对其进行初始化,或者仅在 if 语句中返回它。
    • 现在我收到一个编译器错误,指出 MazeLocationList 是抽象的,无法实例化。程序应该做的是返回一个 MazeLocationList 的实例,如果 findpath 方法没有路径,那么它只返回 null。我只是对返回和 MazeLocationList 实例的含义感到困惑。
    • 好吧,我看不到 MazeLocationList 类的实现,但如果它的抽象意味着它是一个无法实例化的类。我不知道您的整个代码的想法,但是通过创建可以实例化的继承子类来使用抽象类。
    猜你喜欢
    • 1970-01-01
    • 2015-09-30
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多