我是一名使用抽象数据类型“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;
}
}
}