user2228741 user2228741 - 3 months ago 24
Java Question

Can I create an object for a class from an imported package

I am a beginner at java.

I have imported a package in the code and want to use the functions from the imported class. It says object cannot be resolved.

The code is as follows

import edu.princeton.cs.algs4.WeightedQuickUnionUF;

public class Percolation {
private int[] full;
private int length;
private int size;

public Percolation(int n) {
length = n + 2;
WeightedQuickUnionUF uf = new WeightedQuickUnionUF(length);

}

// Now if I use the uf object in another function as below

public boolean isFull(int i, int j) {
boolean result = false;
if(uf.connected(0,i+j)) {
result = true;
}
return result;
}
}

//uf.connected in the public function declared in WeightedQuickUnionUF package.
//Its definition is as follows
public boolean connected(int p, int q) { /* ... */ }


It gives me an error

Error: uf cannot be resolved


uf.connected
in the public function declared in
WeightedQuickUnionUF
package.
Its definition is as follows

public boolean connected(int p, int q) { /* ... */ }


Please advice how to access the function from the imported package.
Thanks in advance!

Answer

You created the variable uf inside the constructor, and it means the other functions will not be able to see it/use it.

As someone already said above, you can either, for example, create the WeightedQuickUnionUF object inside isFull() function, or, since you want the length and you receive it as a parameter in the constructor do something like:

//now uf is a local variable inside a Percolation object
private WeightedQuickUnionUF uf;

public Percolation(int n) {              
    length = n + 2;
    //now uf is created whenever you create a Percolation object
    uf = new WeightedQuickUnionUF(length);
}

Now you can access it in isFull() method!