简体   繁体   中英

How do I initialize this specific variable? [closed]

So I have this method:

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;
    }
}

What I'm trying to do is I'm trying to check if the method findPath returns true or false and then returns different things depending on if it's true or false. The problem is the variable path hasn't been initialized and I'm not quite sure how to initialize it because I want to return path if it's the method findPath is true.

There is a major flaw in your code.

path is a method local variable. So, it cannot be accessed in other methods unless it is passed as an argument.

Since in your findPath method, you don't get / pass path , returning path actually makes little sense.

You could initialize path to either null or new MazeLocationList() but it won't do any good since path is not being changed.

Your variable path doesnt get any value at all, so it doesnt matter if it is initialized or not.

What is the idea of returning path if the value is never changed?

EDIT:

If you only want to return an instance of MazeLocationList , just do

MazeLocationList path = new MazeLocationList();

or instead of returning path, return an instance:

return new MazeLocationList();

Like that:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM