编译期间的Int初始化错误

pas*_*ear 1 java compiler-errors initialization

我是一名学生正在研究一个使用抽象数据类型"ArrayIntLog"的简单程序(TestLuck).它应该生成用户确定的日志量,并使用"compare()"方法检查在找到匹配项之前循环的日志条目数.我收到这个错误:

TestLuck.java:27:错误:变量totalRuns可能尚未初始化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;          
      } 
   }
}
Run Code Online (Sandbox Code Playgroud)

rge*_*man 6

在Java中,局部变量总是需要在使用之前进行初始化.在这里,您没有初始化totalRuns(仅upperLimit在此处初始化).

int totalRuns, currentRun, upperLimit = 0;
Run Code Online (Sandbox Code Playgroud)

给它(和currentRun)一个显式值.

int totalRuns = 0, currentRun = 0, upperLimit = 0;
Run Code Online (Sandbox Code Playgroud)

此行为由JLS,第4.12.5节指定:

局部变量(§14.4,§14.14)必须在使用之前通过初始化(第14.4节)或赋值(第15.26节)明确赋值.