2017-09-03 150 views
0

我有這樣的代碼在這裏:隨機數未初始化

Random rand = new Random(); 
    int randomNum; 
    int i; 
    String[] text1 = getResources().getStringArray(R.array.text1); 
    String[] text2 = getResources().getStringArray(R.array.text2); 



    for(i = 0; i < ((MAX - 1)^(MAX - 1)); i++) { 
     randomNum = rand.nextInt(2); 
     // True wenn bereits angezeigt worden 
     if(shown_table.get(randomNum)) { 
      continue; 
     } 
     // False wenn noch nicht angezeigt worden 
     else { 
      break; 
     } 
    } 

    // Texte anzeigen und Shown table auf true setzen. 
    txt_text1.setText(text1[randomNum]); 
    txt_text2.setText(text2[randomNum]); 
    //shown_table.put(randomNum, true); 

但是,當我編譯它,我得到這個錯誤:

Error:Execution failed for task ':app:compileDebugJavaWithJavac'. 
> Compilation failed; see the compiler error output for details. 
Error:(118, 33) error: variable randomNum might not have been initialized 

當我把「randomNum = rand.nextInt(2 );「在循環之前它工作...但那不是我想要的。

任何想法爲什麼?

PS:我是新來的編碼

+1

'^'不應該計算Java中設置的功率。這是XOR。 https://stackoverflow.com/questions/1991380/what-does-the-operator-do-in-java –

回答

2

XOR具有的屬性,所有X,X^X == 0,所以表達式(MAX - 1)^(MAX - 1)總是計算爲零,並且您的代碼永遠不會進入循環。

但這不是問題。編譯器總是假定循環可能永遠不會被執行,並且它會抱怨在這種情況下,randomNum在用作數組下標時不會被初始化。

+0

感謝這些信息,但現在我有這個問題:'無法啓動活動ComponentInfo {com.example.alex.wouldyoupressthebutton/com.example.alex.wouldyoupressthebutton.MainActivity}:java.lang.NullPointerException:試圖調用虛擬方法' java.lang.Object java.util.Hashtable.get(java.lang.Object)'null object reference' – MrMinemeet

+0

@MrMinemeet它看起來像'shown_table'爲空。 –

+0

@MrMinemeet看看:https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it –

1

編譯器不能從「randomNum」將被初始化爲for循環可能是空的代碼保證。這就是爲什麼行txt_text1.setText(text1[randomNum]);不應該編譯。

如果您是確保執行將始終進入循環,與任何大致合理的值初始化,如int randomNum=0;

+0

這有助於thx。 – MrMinemeet