2013-08-29 162 views
1

我是一名學生,學習使用抽象數據類型「ArrayIntLog」的簡單程序(TestLuck)。它應該生成一個用戶確定的日誌量,並使用「compare()」方法檢查找到匹配之前循環的日誌條目數。我得到這個錯誤:編譯期間的初始化錯誤

TestLuck.java:27: error: variable totalRuns might not have been initialized totalRuns += currentRun; ^

我如何初始化這些變量是錯誤的?它是否與我在for循環中使用它們的事實有關?

public class TestLuck{ 
    public static void main (String [] args){ 

     Random rand = new Random(); 
     int n = rand.nextInt(100); // gives a random integer between 0 and 99. 
     Scanner kbd = new Scanner(System.in); 
     double average = 0; 
     int totalRuns, currentRun, upperLimit = 0; 

     System.out.println("Enter the upper limit of the random integer range: "); 
     ArrayIntLog arr = new ArrayIntLog(kbd.nextInt()); 
     System.out.println("Enter the number of times to run the test: "); 
     int numTests = kbd.nextInt(); 

     for(int j=0; j<=numTests; j++){ 
     for(int i=0; i<arr.getLength(); i++){ //loops through ArrayIntLog and loads random values 
      n = rand.nextInt(100); 
      arr.insert(n); //insert a new random value into ArrayIntLog 
      if(arr.contains(n)){ 
       currentRun = i+1; 
       i = arr.getLength(); 
      } 
     }  
     totalRuns += currentRun; 
     currentRun = 0;   
     } 
    } 
} 
+0

可變totalRuns可能沒有被初始化totalRuns + = currentRun; 我真的認爲這說明了一切。 – Cruncher

回答

6

在Java中,局部變量總是需要在使用前進行初始化。在這裏,你沒有初始化totalRuns(這裏只有upperLimit被初始化)。

int totalRuns, currentRun, upperLimit = 0; 

給它(和currentRun)一個明確的值。

int totalRuns = 0, currentRun = 0, upperLimit = 0; 

此行爲是由JLS,4.12.5節規定:

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26)...

+0

和currentRun也應該初始化 – DRastislav

+0

@DRastislav你說得對。糾正。 – rgettman

0

您聲明

int totalRuns, currentRun, upperLimit = 0; 

但不初始化totalRuns。所以

totalRuns += currentRun; 

沒有要添加的值。它初始化爲默認值,例如0(同他人)

int totalRuns = 0; 
1
int totalRun, currentRun, upperLimit = 0; 

局部變量必須在使用前進行初始化。

例子:

int totalRun=0, currentRun=0, upperLimit = 0;