随机模拟器

use*_*882 0 java random die

你好stackoverflow你总是很好,乐于助人.我的随机模拟器遇到了另一个编译问题;

public class dieSimulator
{
    public static void main(String[] args)
    {
        die();
    }
    public static int die()
    {
        generator.nextInt(6)+1;
    }
}
Run Code Online (Sandbox Code Playgroud)

它基本上应该在每次运行程序时生成1到6之间的随机int.

任何帮助将不胜感激,谢谢!

编辑:谢谢,这是我当前的代码,仍然给我编译器错误:错误:找不到符号返回generator.nextInt(6)+1; ^符号:变量发生器

public class dieSimulator
{
    public static void main(String[] args)
    {
        int rollValue = die();
        System.out.println(rollValue);
    }
    public static int die()
    {
        return generator.nextInt(6)+1;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在阅读的这本书告诉我",调用generator.nextInt(6)给你一个0到5之间的随机数".

编辑结束; 使魔术发生的最终代码

    import java.util.Random;

public class dieSimulator
{
    public static void main(String[] args)
    {
        int rollValue = die();
        System.out.println(rollValue);
    }
    public static int die()
    {
        Random generator = new Random();
        return generator.nextInt(6)+1;
    }
}
Run Code Online (Sandbox Code Playgroud)

Sud*_*hul 5

您需要return生成的值,因为die()它具有返回类型int但方法中没有return语句,因此抛出了编译错误.

public static int die()
{
    return generator.nextInt(6)+1; // return the value
}
Run Code Online (Sandbox Code Playgroud)

并且您需要在调用方法中将返回的值分配给某个int变量(以便以后可以使用它).

public static void main(String[] args)
{
    int rollValue = die();
    // Do something with rollValue 
}
Run Code Online (Sandbox Code Playgroud)

问:谢谢,这是我当前的代码,仍然给我编译错误:错误:找不到符号返回generator.nextInt(6)+1; ^符号:变量发生器

由于您没有generator在类中的任何位置定义,因此无法找到它.它应该在你的班级中定义.像这样的东西

public class dieSimulator
{
    Random generator = new Random(); //Just as an example
    ...
Run Code Online (Sandbox Code Playgroud)