2016-04-11 49 views
0

我有以下代碼,其中變量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應該初始化?

+1

控制可能不會進入for循環,所以你必須初始化它 – Subhiksh

+0

感謝您的回答,但爲什麼它可能不會進入循環內,你能告訴我原因嗎?@Subhiksh – iceiceice

回答

2

基本上,由於Java的工作方式,gcd需要在某些時候聲明。

您的方法聲明int gcd但從未爲您的if語句內部賦值。有可能你的if語句永遠不會被輸入,因爲它裏面的布爾語句從不計算爲真。在這種情況下,會出現問題,因爲即使沒有賦值,也會執行return gcd;。 Java不希望發生這種情況,並警告你。

您可能想要設置一個默認值,以防它找不到gcd。這個值顯然是1,所以聲明如下:int gcd = 1;

+0

感謝您的幫助。 – iceiceice

-4
  • 第一件事是每個變量必須在使用前初始化。
  • 編譯器會這樣做,以確保在執行或在程序中使用變量時,變量中至少有一個值。
  • 避免編譯時錯誤。這是使用。
  • 在你的情況下,如果值N1N2是0,那麼控制不會進入for循環和GCD將不會被初始化。在返回gcd值的同時,編譯時錯誤將會出現
  • 我也想從Java文檔指出這部分,

    Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

    你可以得到完整的文檔中this鏈接。

    貸記卡SO Question

    這說,作爲你的GCD是一個局部變量這就是爲什麼它不使用默認值初始化。

  • 因此您必須初始化該變量。

  • 這是你應該做 - 什麼

    public static int gcd(int n1, int n2) { 
    int gcd = 0; 
    for (int n = 1; n <= n1 && n <= n2 ; n++) { 
    if (n1 % n == 0 && n2 % n == 0) 
        gcd = n; 
    } 
    return gcd; 
    
    } 
    

    int gcd = 0;

希望這個答案可以幫助你。

+1

基元不能爲空 –

+0

我完全不同意你。看到我編輯的答案@RaphaelRoth。 –

+0

不嚴重,**基元不能爲空。** – Makoto