2 回答
TA贡献1873条经验 获得超9个赞
从技术上讲,如果您不想返回 null(顺便说一句,这看起来不错),则有两种选择:
返回一个包含两个返回值的对象
传入一个可变对象作为参数。
第二种选择也感觉有些脏。
TA贡献1776条经验 获得超12个赞
java 是一种按值调用的语言,但它有点复杂。这种语言将指针作为值传递,如果您不更改指针,则可以更改传递给函数的对象。例如,如果您将一个复杂对象传递给一个函数,并且在该函数中您更改了该对象的参数值,则调用者可以看到它,在您的代码中,您可以传递一个包含 dir 和 isLocked 的对象,因此您可以更改那些参数。
Place followDirection(MyObject obj) {
obj.dir = obj.dir.toLowerCase(); // make sure the string is lowercase for comparisons
int i = 0;
for ( i = 0; i < directions.size(); i++ ) { // loop until we find a match, remember that if it's locked then we cnanot go in there
if ( directions.get(i).getDirection().equals(obj.dir) ) {
if ( directions.get(i).isLocked() ) {
System.out.println("This room is locked, sorry");
}
else {
return directions.get(i).getToPlace(); // this means we found a match, return the destination
}
}
}
Place p = null;
return p;
}
MyObject 包含:
String dir, boolean isLocked
添加回答
举报