简体   繁体   中英

Java compile missing return statement error

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

}

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
}

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").

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM