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

标签 java compiler-errors initialization

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

相关文章:

java - 不初始化局部变量并将属性(整数)初始化为 0 背后的逻辑是什么?

class - 子类的Kotlin变量初始化对于将值初始化为0的行为很奇怪

java - eclipse java资源泄漏

java - Spring Data 可分页 : Returns empty content

visual-studio-code - 如何在Visual Studio Code SERVER上运行/编译Pascal? (在Ubuntu上使用FPC吗?)

swift - 编译器不喜欢完成处理程序中的保护语句

matlab - 我在初始化 MATLAB 类时遇到问题

java - Google Map Android API 可以加载的最大 KML 文件大小

java - 使 RecyclerView 中的项目可点击时出现问题

c++ - Xcode 4 中的 boost::asio::ssl 链接错误