繁体   English   中英

如何在不破坏当前代码的情况下修复错误“此方法必须返回 int 类型的结果”?

[英]How can I fix the error "This method must return a result of type int" without breaking the current code?

据我所知,我理解这个错误。 我知道在我的程序中存在不满足任何条件并且计算机不知道该怎么做的情况。 话虽如此,我不确定如何在不破坏当前代码的情况下正确修复它。 我在所有 if 语句的末尾添加了一个 return 0,它消除了错误,但在某些情况下,0 会打印出我当然不想要的。 我也尝试将它放在最后的 else 语句中,但我仍然遇到相同的错误。

赋值说明如下:“如果两个参数在1以内,则返回较小的数;否则,从较大的参数中减去1,在较小的参数上加1,平衡结果。”

这是我所拥有的:

    public static int balance (int x, int y) {
        if(x == y) {
            System.out.println("The values X and Y (" + x +  " and " + y + ") are already balanced; They are equal to each other!");
        }
        
        else if(Math.abs(x-y) == 1) { //Checks to see if numbers are within 1 of each other (Math.abs because negative numbers don't matter in this case)
            if(x > y) {
                return y;
            }
            else return x;
        }
        else if(x > y) {
            x = x - 1; //X is larger so we subtract
            y = y + 1; //Y is smaller so we add
            return balance(x,y); //Recursion happens
        }
        else if(x < y) {
            y = y - 1; //Y is larger so we subtract
            x = x + 1; //X is smaller so we add
            return balance(x,y); //Recursion happens
        }
    }

那一边的计算和所有内容似乎都按照说明要求进行。 我似乎无法摆脱“此方法必须返回 int 类型的结果”错误,而无需在控制台中显示不需要的随机值。

您需要进行两项更改。

  1. 决定在x == y的情况下返回什么,并将适当的return语句添加到第一个分支。

  2. else if (x < y) {更改为else { 你知道你已经用尽了所有的可能性,但编译器没有。 这是告诉编译器没有其他地方可以结束的可靠方式。

除非你做这两件事,否则编译器认为它可能会在方法中用完要执行的行,而不会遇到return语句。 这对于您声明为返回int的方法无效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM