为什么在方法中使用Math函数时返回语句会抛出错误。
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));
}
}
这可能有帮助,也可能没有帮助,但IMOwhile(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
。
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
语句而不是break
语句。因此,方法hcfreturn res;
的最后一行在任何条件下都是不可达的。
if-else
中代码的分段导致return res
的最后一行无法访问,因此您必须做两件事:
- 删除
if
内部的返回并添加break - 返回方法的最后一行,即
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));
}
}