The variable may not have been initialized with an 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
  }
}
+3
source share
4 answers

You declared it without initialization. Give it the initial value before the while loop, so the compiler is sure that the variable contains no garbage.

int total = 0;
+1
source

Inside the while loop, execution is not guaranteed - for example, if timesless than zero from a programming error. The compiler knows this, so it will not count on a while loop when it is determined whether it has been initialized total.

+4
source

Java.

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

. , , () ​​ int loop.It .

0

Source: https://habr.com/ru/post/1785275/


All Articles