Mac
Mac

Reputation: 35

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
  }
}

Upvotes: 3

Views: 1693

Answers (4)

Tofiq
Tofiq

Reputation: 3001

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.

Upvotes: 0

Navi
Navi

Reputation: 8736

You are required to initialize local variables in Java.

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

Upvotes: 0

Bill the Lizard
Bill the Lizard

Reputation: 405675

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;

Upvotes: 1

jprete
jprete

Reputation: 3759

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.

Upvotes: 4

Related Questions