質問

Hello stackoverflow you're always so nice and helpful. I've encountered another compiling-problem with my random-diesimulator;

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

It's basically supposed to generate a random int between 1 and 6 each time the program is run.

Any help would be appreciated, thank you!

EDIT: Thank you, here's my current code, still giving me the compiler-error: error: cannot find symbol return generator.nextInt(6)+1; ^ symbol: variable generator

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

The book I'm currently reading tells me that ",the call generator.nextInt(6) gives you a random number between 0 and 5".

EDIT END; The final code that made the magic happen

    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;
    }
}
役に立ちましたか?

解決

You need to return the generated value because die() has a return type of int but there is no return statement in the method, thus throwing a compilation error .

public static int die()
{
    return generator.nextInt(6)+1; // return the value
}

And you need to assign the returned value to some int variable(so that you can use it later) in the caller method.

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

Q. Thank you, here's my current code, still giving me the compiler-error: error: cannot find symbol return generator.nextInt(6)+1; ^ symbol: variable generator

Since you don't have the generator defined anywhere in the class, it is not able to find it. It should be defined in your class. Something like this

public class dieSimulator
{
    Random generator = new Random(); //Just as an example
    ...

他のヒント

you missed return statement..

public static int die()
{
    return generator.nextInt(6)+1;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top