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
}
}
答案 0 :(得分:4)
不能保证while循环的内部执行 - 例如,如果times
从编程错误中小于零。编译器知道这一点,所以在确定total
是否被初始化时,它不会依赖于while循环。
答案 1 :(得分:1)
您已声明而没有初始化它。在while循环之前给它一个初始值,这样编译器就可以确定该变量不包含垃圾。
int total = 0;
答案 2 :(得分:0)
您需要在Java中初始化局部变量。
int total = 0; //here it is
int c = 0;
答案 3 :(得分:0)
你没有初始化刚刚声明的总数。如果循环不执行时,总和不等于任何值,因为变量(角色)声明并且初始化为循环。最好在循环之前声明和初始角色。