gpt4 book ai didi

java - 编译期间 Int 初始化错误

转载 作者:行者123 更新时间:2023-11-29 06:37:24 25 4
gpt4 key购买 nike

我是一名学生,正在研究一个使用抽象数据类型“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;
}
}
}

最佳答案

在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)...

关于java - 编译期间 Int 初始化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18518362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com