custom java package doesn't work

2019-08-16 09:25发布

问题:

I am trying to create a custom package to put some of my classes, but when I try to import it into one of my programs, it says it cant be found.

This is the file I am trying to compile but it is saying the package cannot be found

import project_euler.Fibonacci;

public class test {
    public static void main(String[] args) {
        Fibonacci fib = new Fibonacci();
        System.out.println(fib.getTerm(10));
    }
}

This is the Fibonacci class

package project_euler;
public class Fibonacci {
    public int getTerm(int n) {
        if (n < 0 || n > 46) {
            throw new IllegalArgumentException();
        } else {
            return (n > 1) ? getTerm(n-1) + getTerm(n-2) : n;
        }
    }
}

This is the errors I get when I try to compile

test.java:1: error: package project_euler does not exist
import project_euler.Fibonacci;
                ^
test.java:6: error: cannot access Fibonacci
            Fibonacci fib = new Fibonacci();
            ^
bad source file: C:\Users\dhout_000\Documents\Project Euler\project_euler\Fibonacci.java
file does not contain class Fibonacci
Please remove or make sure it appears in the correct subdirectory of the sourcepath.
2 errors

And my directory set up is

> My Documents
    > Project Euler
        - test.java
        > project_euler
            - Fibonacci.class
            - Fibonacci.java

I just cant seem to figure out what the problem is

回答1:

Make sure you do not have the CLASSPATH environment variable set.

Compile and run your code from the base directory of the package hierarchy.

C:\My Documents\Project Euler> javac project_euler\Fibonacci\*.java

C:\My Documents\Project Euler> java project_euler.Fibonacci.test

You can also explicitly specify the classpath using the -cp option for the javac and java commands. Make sure that the base directory of the package hierarchy (C:\My Documents\Project Euler) is included. You could do this by specifying . (the current directory) when you're in C:\My Documents\Project Euler:

C:\My Documents\Project Euler> javac -cp . project_euler\Fibonacci\*.java

C:\My Documents\Project Euler> java -cp . project_euler.Fibonacci.test

Note: According to the common Java naming conventions, you shouldn't use underscores in names (package, class, method names), package names should be lower-case and class names should start with a capital letter. Rename the package to projecteuler.fibonacci (you'll need to rename the folders too, ofcourse), and rename the class test to Test.



标签: java packages