这是我的方法:
public int power(int x, int n) {
switch (n) {
case 2: return square(x);
case 3: return cube(x);
case 4: return hypercube(x);
}
}
编译器显示此消息:
Method breakpoint:Tester [entry] - power(int, int) - This method must return a result of type int" message.
似乎无法弄清楚问题是什么。
我知道这是不好的做法,但我被指示不要将值存储在局部变量中并在最后返回它。
我在这里错过了什么?
最佳答案
如果 n
不是您的情况之一,则不会返回任何内容 - 这就是编译器所提示的。
由于您的实现只满足 n 为 2、3 和 4,最合适的做法是抛出异常:
public int power(int x, int n) {
switch (n) {
case 2: return square(x);
case 3: return cube(x);
case 4: return hypercube(x);
}
throw new IllegalArgumentException("Power must be 2, 3 or 4. Unsupported power: " + n);
}
然后编译器将满足于所有代码路径要么返回一些东西要么抛出异常。
关于java - 方法不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33977098/