I\'ve downloaded two jars. I want to import some of their contained classes. How do I do this?
It\'s for my algorithms class. I\'ve tried following the instructions
Launch javac with the -classpath <path_to_jar>
option. Or edit the CLASSPATH environment variable so that it contains the JAR with the classes you wish to use.
If you are getting the "cannot be resolved to a type" error, and have tried adding the stdlib.jar or algs4.jar files, here is the solution:
The libraries in stdlib.jar and algs4.jar are in the "default" package. In Java, you can't access classes in the default package from a named package. If you need to use the libraries with a named package, you can use these package versions:
stdlib-package.jar and algs4-package.jar.
You can download these files here: http://algs4.cs.princeton.edu/code/
Then you can automatically add the import: import edu.princeton.cs.algs4.ClassName
I wasted a lot of time with importing the class, tried the CL option of "javac -cp .;stdlib.jar mad.java" etc but used to get the same error you mentioned.
I then commented out the import altogether and made sure the DrJava's preferences had the 2 classpaths added + the %CLASSPATH% variable to have the right value. Is simply works now.
Good luck!
You probably have the classpath stuff right. The class you're trying to import may not be called java.stdlib
though. You need to import the fully qualified package name ... probably something like org.somecompany.ourlibrary.stdlib
. Thus you would need
import org.somecompany.ourlibrary.stdlib
at the top of your Percolations.java
file with the rest of the import statements.
It is outdated to answer this question, but maybe it will be useful for future participants of Princeton Algorithms course. After adding CLASSPATH in environment java get classes from packages but still will generate errors on import command. You need to delete import algs4 and stdlib from source files and compilation will run smoothly.
This solution works on Ubuntu 12.04 with zsh.
If you're using Eclipse (as I do), select the current project, then you open the project properties from the menus. On the left you select "Java Build path", and then you select the tab libraries. Now you click the button "Add external Jars" and you point to your jar files, and you're done.
Good luck.