我有以下代碼,其中變量gcd
是GCD()函數中,這是示出了錯誤:局部變量GCD可能沒有被初始化
The local variable gcd may not have been initialized.
的代碼是:
import java.util.Scanner;
public class GreatestCommonDivisorMethod {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter two numbers");
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt();
System.out.println("the gcd of the " + num1 + " and " + num2 + " is " + gcd(num1,num2));
}
public static int gcd(int n1, int n2) {
int gcd ;
for (int n = 1; n <= n1 && n <= n2 ; n++) {
if (n1 % n == 0 && n2 % n == 0)
gcd = n;
}
return gcd;
}
}
爲什麼gcd
應該初始化?
控制可能不會進入for循環,所以你必須初始化它 – Subhiksh
感謝您的回答,但爲什麼它可能不會進入循環內,你能告訴我原因嗎?@Subhiksh – iceiceice