我是一名學生,學習使用抽象數據類型「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;
}
}
}
可變totalRuns可能沒有被初始化totalRuns + = currentRun; 我真的認爲這說明了一切。 – Cruncher