【问题标题】:Why does return statement is throwing error when used Math function in a method为什么在方法中使用数学函数时返回语句会抛出错误
【发布时间】:2021-02-28 00:13:41
【问题描述】:

为什么在方法中使用数学函数时返回语句会抛出错误。

public class HCF_1 {
    
    static int hcf(int a, int b)
    {
        int res = Math.max(a,b);
        while(true)
        {
            if(res%a==0 && res%b==0)
                return res;
            else res++;
        }
        return res;
    }
    public static void main(String[] args) {
        
        System.out.println(hcf(5,25));
    }
}

【问题讨论】:

  • 无法访问。将第一个 return 替换为 break。或者删除第二个return
  • 顺便说一下,一旦你修复了错误,按照蓬松的建议,这不会给你 hcf;它会给你 lcm。
  • 能否请您善待并发布错误消息?

标签: java


【解决方案1】:

这可能有帮助,也可能没有帮助,但 IMO while(true) 语句是真正的代码气味。您可以将此方法重写为:

public class HCF_1 {
   
   static int hcf(int a, int b)
   {
       int res = Math.max(a,b);
       while(res % a != 0 || res % b != 0)
           res++;
       return res;
   }
   public static void main(String[] args) {
       System.out.println(hcf(5,25));
   }
}

现在只有一个 return 语句,没有捷径。

注意,!(res % a == 0 && res % b == 0) 的操作与res % a != 0 || res % b != 0 相同,这是由于布尔逻辑的属性:~(A AND B) == ~A OR ~B

【讨论】:

    【解决方案2】:
    public class HCF_1 {
            
            static int hcf(int a, int b)
            {
                int res = Math.max(a,b);
                while(true)
                {
                    if(res%a==0 && res%b==0)
                        return res;
                    else res++;
                }
                return res; //last line of the method hcf is unreachable
            }
            public static void main(String[] args) {
                
                System.out.println(hcf(5,25));
            }
        }
    

    while 循环是一个永无止境的循环,只有在 if 块中提到的条件下才会转义,该条件是 return statement 而不是 break 语句。因此方法 hcf return res; 的最后一行在任何情况下都无法访问。

    【讨论】:

      【解决方案3】:

      if-else 中的代码段导致return res 的最后一行无法访问,因此您必须做两件事:

      1. 删除 if 中的 return 并添加 break 代替。
      2. 返回方法的最后一行return res;
      public class HCF_1 {
      
          static int hcf(int a, int b) {
              int res = Math.max(a, b);
              while (true) {
                  if (res % a == 0 && res % b == 0)
                      break;
                  else
                      res++;
              }
              return res;
          }
      
          public static void main(String[] args) {
      
              System.out.println(hcf(5, 25));
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-12
        • 1970-01-01
        • 2016-07-29
        • 2017-07-11
        • 1970-01-01
        • 2014-09-12
        • 2022-01-20
        • 2017-03-08
        相关资源
        最近更新 更多