简体   繁体   中英

Variable might not have been initialized error in Java

import java.util.Random;

public class dice
{
  private int times;
  private int roll;
  private int side;
  Random roller = new Random();   

  public void setTimes(int sides)
  {
    times = sides;
  }

  public void setSides(int die)
  {
    side = die;
  }

  public int getRoll()
  { 
    int total; //here it is
    int c = 0;
    while (c <= times)
    {
      c = c + 1;
      int rol = 0;
      roll = roller.nextInt(side) + 1;
      rol = rol + roll;
      total = rol; //here it is initialized
    }
    return total; //here it says variable not initialized
  }
}

The inside of a while loop isn't guaranteed to execute - for example, if times is less than zero from a programming mistake. The compiler knows this, so it won't count on the while loop when figuring out whether total was initialized.

You've declared it without initializing it. Give it an initial value before the while loop so the compiler is sure the variable doesn't contain garbage.

int total = 0;

You are required to initialize local variables in Java.

int total = 0; //here it is
int c = 0;

你没有初始化刚刚声明的总数。如果循环不执行时,总和不等于任何值,因为变量(角色)声明并初始化循环。最好在循环之前声明和初始角色。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM