英文:
I have a method that returns a int, and it tells me i'm missing a return statement. Can this be fixed without rewriting the method?
问题
这是该方法。正如您所见,所有的if语句中都有一个返回,所以我理解为什么它不能识别输出,但是否有任何方法可以修复这个问题?
private int bounds(int x, int y) {
if (x == -1) {
if (y == -1) {
return life[130][70];
} else if (y == 71) {
return life[130][0];
}
if (0 <= y && y <= 70) {
return life[130][y];
}
} else if (x == 131) {
if (y == -1) {
return life[0][70];
} else if (y == 71) {
return life[0][0];
}
if (0 <= y && y <= 70) {
return life[0][y];
}
}
if (0 <= x && x <= 130) {
if (y == -1) {
return life[x][70];
} else if (y == 71) {
return life[x][0];
}
if (0 <= y && y <= 70) {
return life[x][y];
}
}
}
英文:
This is the method. As you can see, all of the if statements have a return in them so I understand why it is not recognizing the output, but is there any way to fix this?
private int bounds(int x, int y) {
if (x == -1) {
if (y == -1) {
return life[130][70];
}
else if (y == 71) {
return life[130][0];
}
if (0 <= y && y <= 70) {
return life[130][y];
}
}
else if (x == 131) {
if (y == -1) {
return life[0][70];
}
else if (y == 71) {
return life[0][0];
}
if (0 <= y && y <= 70) {
return life[0][y];
}
}
if (0 <= x && x <= 130) {
if (y == -1) {
return life[x][70];
}
else if (y == 71) {
return life[x][0];
}
if (0 <= y && y <= 70) {
return life[x][y];
}
}
}
答案1
得分: 1
请问您的方法在例如 x 为 -2 时会返回什么。
意思是,编译器会告诉您该方法中存在一些路径没有看到返回语句。简单来说:相信编译器。
您可以通过在所有的 if 块之后添加一个最终的返回语句来修复这个问题。
但是真正的答案是:您不应该编写如此复杂的代码。上述代码会成为一个维护的噩梦。它应该进行重构。
英文:
Ask yourself what your method would return if x is -2 for example.
Meaning: the compiler tells you that there are paths through that method that don't see a return statement. Simply: believe the compiler.
You could fix the problem by adding one final return statement after your if blocks.
But the real answer: you should never write code that turns that complicated. The above is a maintenance nightmare. It should be refactored.
答案2
得分: 0
你需要在函数末尾添加一个默认返回语句,以防如果语句都不成立的情况。
英文:
you need to add a default return to the end of your function, if not one of the if statement is true
答案3
得分: 0
可以通过以下方式修复缺少返回语句的编译错误,而无需重写方法:
- 抛出 RuntimeException(仅当某些输入有效时)。
- 在结尾处返回默认值(如果所有输入都有效)。
在现有逻辑中,负整数(除了 -1 之外的)未经处理(x 和 y 的上限也是如此)。如果当前未处理的输入无效,则可以执行类似以下操作:
private int bounds(int x, int y) {
...
(现有逻辑)
...
throw new IllegalArgumentException("Bad input");
}
英文:
It is possible to fix the missing return statement compilation error without rewriting the method by:
- Throwing a RuntimeException (if only some inputs are valid).
- Returning a default value at the end (if all inputs are valid).
In the existing logic, negative integers other than -1 are not handled (same with upper bounds for x and y). If inputs which are not currently handled are invalid, you may do something like:
private int bounds(int x, int y) {
...
(Existing logic)
...
throw new IllegalArgumentException("Bad input");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论