0

I am trying to learning java, by goofing around and creating different things such as this dice example. However, in the class below I am stuck on this missing return, but I am not sure why. All help is appreciated!

Test1.java:12: error: missing return statement } ^ 1 error

import java.util.Random;

class Char
{
    Random r = new Random();
    int nSides;

    public int Die(int sides)
    {
        this.nSides = sides;
        r = new Random();   
    }

    public int roll()
    {
        return r.nextInt(nSides + 1);
    }

    public int roll(int times)
    {
        int sum = 0;
        for (int i = 0; i < times; i++)
        {
        sum += roll();
        }
        return sum;
    }

}

4 Answers 4

2

It looks like you were trying to write a constructor, which naturally has no return value. A constructor must have the same name as the class that it constructs.

Replace public int Die with the following.

public Char(int sides)
{
    this.nSides = sides;
    r = new Random();   
}

Alternately, you can rename your class Die.

public class Die {
    public Die(int sides)
    {
       this.nSides = sides;
       r = new Random();   
    }
// Rest of your code
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need to say

public Char(int sides)

or, assuming that you want the class really to be called "Die", change the class declaration to:

class Die

and the constructor (?) line to:

public Die(int sides)

(removing the "int").

Comments

0

In function Die apply return statement:

public int Die(int sides)
{
    this.nSides = sides;
    r = new Random(); 
    return 0; // whatever you want to return 
}

or remove int before die and make it void.

public void Die(int sides)
{
    this.nSides = sides;
    r = new Random(); 
}

Comments

0

Looks like you're trying to create a class called Die and that's meant to be its constructor. Try this:

import java.util.Random;

class Die {
    private Random r = new Random();
    private final int nSides;

    public Die(int sides) {
        this.nSides = sides;
    }

    // rest of class omitted
}

Notes:

  • Constructors don't declare a return type and are named the same as the class.
  • No need to re-initialize the Random field (line removed)
  • Better to declare nSides as final (see code)
  • Better to make all fields private

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.