Adar Hefer Adar Hefer - 4 years ago 168
Java Question

Using classes in my project that originate in a jar file

I'm using Eclipse on a Windows 7 64x machine. I've researched this problem and found many have had a similar one, but no solution I came across quite worked for me.

I'm working on a Project named

Assignment_1
, on a class named
Percolation
. I'd like to use the object
WeightedQuickUnionUF
which is inside a package contained within a jar file, named
algs4.jar
.

I seem to have added the Jar file I'm interested in to the build-path (it now appears under "Referenced Libraries"). The jar file
algs4.jar
resides in a folder named
lib
inside my project's folder.

However, when I try to declare an object of type
WeightedQuickUnionUF
inside my class, I get an error "
WeightedQuickUnionUF
cannot be resolved to a type".

I tried various
import
commands (including just
import WeightedQuickUnionUF
)before the class declaration and all of them yield the error "The import
so and so
cannot be resolved".

For example, this piece of code yields both of these errors. One at the
import
line, and another at the declaration of the
WeightedQuickUnionUF
object:

package assignment_1_package;
import algs4.WeightedQuickUnionUF;

public class Percolation {

private int[][] grid;
public int gridDimension;
private int opensGrid[][];
private WeightedQuickUnionUF model;

... //rest of class body here


This has baffled me for an entire day and I can't seem to figure this out. Thanks for your efforts.

Edit: here is a link to the class I wish to import: http://algs4.cs.princeton.edu/15uf/WeightedQuickUnionUF.java.html

Answer Source

Assuming you are talking about the algs4.jar of the class http://algs4.cs.princeton.edu/code/ , your import is incorrect you should do :

import WeightedQuickUnionUF;

BUT it's never a good idea to have class in the default package and it's actually not allowed to import a type from the unnamed package: this gives a compilation error. http://docs.oracle.com/javase/specs/jls/se5.0/html/packages.html#7.4.2:

A type-import-on-demand declaration (§7.5.2) imports all the accessible (§6.6) types of a named type or package as needed. It is a compile time error to import a type from the unnamed package.

So in your case to solve your issue just create your classes in the default package so you don't have to do the import at all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download