开发者

Variable might not have been initialized error in Java

开发者 https://www.devze.com 2023-02-04 11:08 出处:网络
import java.util.Random; public class dice { private int times; private int roll; private int side; Random roller = new Random();
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;
 开发者_如何学Go     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;


You don't initial the total just declared.If the loop don't execute when total not equal any value because the variable(role) declared and initial int the loop.It better you declare and initial role before the loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消