Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable might not have been initialized error in Java

Tags:

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
  }
}
like image 635
Mac Avatar asked Sep 22 '26 06:09

Mac


1 Answers

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.

like image 106
jprete Avatar answered Sep 23 '26 23:09

jprete



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!