robjtede
robjtede

Reputation: 746

Java Class/Package interaction

I have two .java files that I trying to compile with javac in OS X terminal.

DieRun.java

package die;

public class DieRun {
    public static void main(String[] args) {

        Die d6 = new Die(6);

    }
}

And Die.java:

package die;

import java.util.Random;

public class Die {

    private int sides;
    private int value;
    private Random rng;

    public Die(int sides) {
        this.sides = sides;
        this.rng = new Random();
        this.value = this.roll();
    }

    public Die(int sides, int seed) {
        this.sides = sides;
        this.rng = new Random(seed);
        this.value = this.roll();
    }

    public int roll() {
        this.value = this.rng.nextInt(this.sides) + 1;
        return this.value;
    }

    public int getValue() {
        return this.value;
    }

}

Using javac *.java they both compile without any errors but when I try to run one of them (eg. java DieRun ) it fails with error: Could not find or load main class DieRun.

Upvotes: 0

Views: 421

Answers (1)

Jason C
Jason C

Reputation: 40396

Your classes are in a package named "die". To run them, you have a few options.

The quick option is to remove the package declaration so they are in the default package. Not the greatest practice in general but perfectly valid for quick one-off applications.

The correct option is:

  1. Put your source files in a subdirectory named "die".
  2. Compile them there (so that the class files are in "die" - this is the actual important part).
  3. Move up to the parent directory and run java die.DieRun.

Directory structure must match package structure. There is slightly more to it, regarding current class path, etc., but this will get you on your feet.

You may wish to read the official tutorial on packages as well.

Upvotes: 4

Related Questions