2015-08-25 130 views
0

當我嘗試在循環外部使用變量「encryptionKey」或它聲明的if語句時,它會拋出編譯錯誤「無法找到符號」..任何想法?我該如何在循環之外使用這個變量?

else if (inputPlainResultArray.length == 4 || inputPlainResultArray.length == 9 || inputPlainResultArray.length == 16) 
{ 
    char[] encryptionKey = inputPlainResultArray; 
    System.out.print("Encryption Key: "); 
    System.out.print(encryptionKey); 
    System.out.println(); 
    System.out.println(); 
    System.out.println(); 
    System.exit(0); 

} 
} 
} 
+1

那些變量超出了範圍。 在java中,作用域被限制爲{}。 只需將該變量聲明移動到頂端,以便它們可以繼續使用。 –

回答

3

那是因爲variable的範圍是在loop/if語句的花括號。你不能像這樣使用它。而是在外面聲明並使用它。

在你的情況下,它會是這個樣子:

char[] encryptionKey = null; 
if (...) 
... 
else if (inputPlainResultArray.length == 4 || inputPlainResultArray.length == 9 || inputPlainResultArray.length == 16) 
{ 
    encryptionKey = inputPlainResultArray; 
    System.out.print("Encryption Key: "); 
    System.out.print(encryptionKey); 
    System.out.println(); 
    System.out.println(); 
    System.out.println(); 
    System.exit(0); 
} 
1

創建方法以外的變量

char[] encryptionKey; 

方法裏面,那麼你可以有

encryptionKey = ... 

唯一的問題是如果你在初始化變量之前嘗試調用它,所以要小心或者採取預防措施如if(encryptionKey==null) return;

4

因爲它是本地變量,這意味着你不能在它聲明的範圍之外訪問它。 你應該看一看on which types of variables exists in Java

在您的特定情況下,你可以使用實例變量,讓你無論是聲明char[] encryptionKey方法外:

public class YourClass{ 
    char[] encryptionKey; 
    // other methods, fields, etc. 
} 

,你就可以在使用這個變量在這個類中的任何地方,或申報方法裏面,else-if範圍之外位:

char[] encryptionKey = null; 
if (...){} 

else if (...){ 
char[] encryptionKey = inputPlainResultArray; 
} 

因此這將是對所有entiti可見在這個特定的方法裏面。

0

您不能從循環外部訪問變量「encryptionKey」,因爲您已將其聲明在循環中。 將聲明移到外面,它將起作用。

char[] encryptionKey;  
else if (inputPlainResultArray.length == 4 || inputPlainResultArray.length == 9 || inputPlainResultArray.length == 16) 
{ 

      encryptionKey = inputPlainResultArray; 
      .... 
} 
0

使用關鍵字,不System.exit(0);

if(condition){ 
     //do something 
     break; 
    } 
+0

這是給你的第二個問題 – isurujay

相關問題