[英]Method must return int
I am writing a program that uses Euclids algorithm of GCD(a, b) = GCD(b, r) r = a%b. 我正在编写一个使用Euclids算法的程序,该算法的GCD(a,b)= GCD(b,r)r = a%b。 I wrote a method that should return an integer for the main method to spit out, yet when I call for it to do this it says that it is not returning an integer. 我写了一个方法,该方法应该为main方法吐出一个整数,但是当我要求它这样做时,它说它没有返回整数。 Here is the code 这是代码
public class Euclid {
public static int GCD(int a, int b)
{
while (b != 0)
{
int r = a%b;
System.out.println("(" +a+ "," +b+ ")");
b = r;
a = b;
if(b == 0)
{
return a;
}
}
}
public static void main(String[] args)
{
System.out.println(GCD(36, 20));
}
}
The compiler can't tell that your method will eventually reach the b == 0
condition and return. 编译器无法告知您的方法最终将达到b == 0
条件并返回。 You can refactor it to: 您可以将其重构为:
int ret = 1;
while (b != 0)
{
int r = a%b;
System.out.println("(" +a+ "," +b+ ")");
b = r;
a = b;
if(b == 0)
{
ret = a;
break;
}
}
return ret;
In the code if b == 0
it will not return an int
or any value for that matter. 在代码中,如果b == 0
,则不会返回int
或任何值。 You must handle this condition, most likely by specifying a default return value. 您必须处理此情况,很可能是通过指定默认返回值。
public static int GCD(int a, int b)
{
while (b != 0)
{
int r = a%b;
System.out.println("(" +a+ "," +b+ ")");
b = r;
a = b;
if(b == 0)
{
return a;
}
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.