gpt4 book ai didi

java - 是否可以一次调用退回多件商品?

转载 作者:行者123 更新时间:2023-12-01 06:27:32 25 4
gpt4 key购买 nike

以下元素是否可以在一次调用中返回多个项目(即两个 GRect)

    private GObject getColidingObject(){
if(getElementAt(ball.getX(), ball.getY()) != null){
return getElementAt(ball.getX(), ball.getY());
}else if(getElementAt(ball.getX() + BALL_RADIUS *2, ball.getY()) != null){
return getElementAt(ball.getX() + BALL_RADIUS *2, ball.getY());
}else if(getElementAt(ball.getX(), ball.getY() + BALL_RADIUS *2) != null){
return getElementAt(ball.getX(), ball.getY() + BALL_RADIUS *2);
}else if(getElementAt(ball.getX() + BALL_RADIUS *2, ball.getY() + BALL_RADIUS *2) != null){
return getElementAt(ball.getX() + BALL_RADIUS *2, ball.getY() + BALL_RADIUS *2);
}else{
return null;
}
}

最佳答案

您只能返回一个值,但您可以将该值设为数组。例如:

private GObject[] getCollidingObjects() {
GObject[] ret = new GObject[2];

ret[0] = ...;
ret[1] = ...;
return ret;
}

顺便说一句,当您开始在同一方法中多次重复使用同一表达式时,为了清楚起见,您应该考虑引入局部变量。例如,考虑这个而不是您的原始代码:

private GObject getCollidingObject(){
int x = ball.getX();
int y = ball.getY();
if (getElementAt(x, y) != null) {
return getElementAt(x, y);
}
if (getElementAt(x + BALL_RADIUS * 2, y) != null) {
return getElementAt(x + BALL_RADIUS * 2, y);
}
if (getElementAt(x, y + BALL_RADIUS * 2) != null) {
return getElementAt(x, y + BALL_RADIUS * 2);
}
if (getElementAt(x + BALL_RADIUS * 2, y + BALL_RADIUS * 2) != null) {
return getElementAt(x + BALL_RADIUS * 2, y + BALL_RADIUS * 2);
}
return null;
}

(您也可以对 x + BALL_RADIUS * 2y + BALL_RADIUS * 2 执行相同的操作。)

您也可以考虑这样的事情:

private GObject getCollidingObject(){
int x = ball.getX();
int y = ball.getY();
return getFirstNonNull(getElementAt(x, y),
getElementAt(x + BALL_RADIUS * 2, y),
getElementAt(x, y + BALL_RADIUS * 2),
getElementAt(x + BALL_RADIUS * 2, y + BALL_RADIUS * 2));
}

private static getFirstNonNull(GObject... objects) {
for (GObject x : objects) {
if (x != null) {
return x;
}
}
return null;
}

(在 C# 中,有一种更好的方法可以使用空合并运算符来执行此操作,但没关系...)

关于java - 是否可以一次调用退回多件商品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1313492/

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