0

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!

vsminkov
  • 10,912
  • 2
  • 38
  • 50
Arpit
  • 79
  • 8
  • 1
    It is outside of the class – Jens Sep 06 '16 at 19:55
  • 1
    well, yeah. You created `uf` in the constructor only. It's discarded right afterwards. If you want to have access to it in the entire class you need to make it a (private) variable. – UnholySheep Sep 06 '16 at 19:55

3 Answers3

2

You have created local variable uf into constructor and try to access it from method isFull().

You can either:

  1. Create object uf into method isFull() and use it
  2. make uf a member of your class and use it.
  3. use call method of uf from constructor.
AlexR
  • 114,158
  • 16
  • 130
  • 208
1

This is a context problem: uf is declared in Percolation's constructor, and is not an attribute of the class.

Faibbus
  • 1,115
  • 10
  • 18
1

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!

Pedro Pinto
  • 179
  • 1
  • 3
  • 14