gpt4 book ai didi

java - java中如何在一个方法中有一个return语句?

转载 作者:行者123 更新时间:2023-12-02 02:13:47 25 4
gpt4 key购买 nike

我知道如何在一些简单的情况下在方法中返回一个值,但是当一个方法从另一个类返回一个对象时,我不知道如何给出一个变量来存储返回值。具体代码如下:

public Path findPath(Maze maze) {
Path path = new Path();
MazePosition initialPos = new MazePosition(0, 0, null);
Stack<MazePosition> posForExplore = new Stack<MazePosition>();
MazePosition pos = initialPos;
MazePosition next;

posForExplore.push(pos);
while (!posForExplore.empty()) {
pos = posForExplore.pop();
switch (maze.getPosStatus(pos)) {
case GOAL:
MazePosition p = pos;
while (p!=null) {
path.insertFirst(p.getCoords()[0], p.getCoords()[1]);
p =p.getFrom();
}
return path;
case VISITED:
break;
case OBSTACLE:
break;
case OPEN:
maze.setPosStatus(pos, MazeStatus.VISITED);
for (Movement mov: DIRS_TO_EXPLORE) {
next = maze.getNeighbour(pos, mov);
if (next!=null&&(maze.getPosStatus(next)==MazeStatus.OPEN||maze.getPosStatus(next)==MazeStatus.GOAL)) {
posForExplore.push(next);
}
}
break;
}
}
return null;
}

我有一个返回路径并且返回null,那怎么可能只有一个return语句呢。非常感谢!

最佳答案

声明path并将其初始化为null。在插入任何内容之前检查 null 并初始化它(打破循环以触发返回)。最后返回路径。就像,

public Path findPath(Maze maze) {
Path path = null;
MazePosition initialPos = new MazePosition(0, 0, null);
Stack<MazePosition> posForExplore = new Stack<MazePosition>();
MazePosition pos = initialPos;
MazePosition next;

posForExplore.push(pos);
loop: while (!posForExplore.empty()) {
pos = posForExplore.pop();
switch (maze.getPosStatus(pos)) {
case GOAL:
MazePosition p = pos;
while (p != null) {
if (path == null) {
path = new Path();
}
path.insertFirst(p.getCoords()[0], p.getCoords()[1]);
p = p.getFrom();
}
break loop;
case VISITED:
break;
case OBSTACLE:
break;
case OPEN:
maze.setPosStatus(pos, MazeStatus.VISITED);
for (Movement mov : DIRS_TO_EXPLORE) {
next = maze.getNeighbour(pos, mov);
if (next != null && (maze.getPosStatus(next) == MazeStatus.OPEN
|| maze.getPosStatus(next) == MazeStatus.GOAL)) {
posForExplore.push(next);
}
}
break;
}
}
return path;
}

关于java - java中如何在一个方法中有一个return语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49582041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com