Reputation: 341
I am new to Java and am having an issue calling a method. I was hoping someone might be able to help me figure out what is going on.
The code I have is as follows:
public class QuickFindUF
{
private int[] id;
public QuickFindUF(int N)
{
id = new int[N];
for (int i = 0; i < N; i++)
id[i] = i;
}
public boolean connected(int p, int q)
{ return id[p] == id[q]; }
public void union(int p, int q)
{
int pid = id[p];
int qid = id[q];
for (int i = 0; i < id.length; i++)
if (id[i] == pid) id[i] = qid;
}
}
I took a look on Stack and figured the way to call my method would be using the following code: QuickFindUF x = new QuickFindUF(10);
When I run this I get an error that says
QuickFindUF.java:27: error: class, interface, or enum expected
QuickFindUF x = new QuickFindUF(10);
^
1 error
If someone could point me in the right direction I would really appreciate it. Thanks.
Upvotes: 0
Views: 309
Reputation: 7730
Your main method might be outside the class , You need to declare main method inside the class like this way :
public static void main(String []args){
QuickFindUF x = new QuickFindUF(10);
}
Upvotes: 1
Reputation: 698
If the code you posted is your complete code, it appears you need a main method.
public class QuickFindUF
{
//
// add this so you can run code when your program executes
//
public static void main(String[] args)
{
QuickFindUF x = new QuickFindUF(10);
//
// call your methods on x here
// e.g.
// boolean connected = x.connected(2, 3);
//
}
private int[] id;
public QuickFindUF(int N)
{
id = new int[N];
for (int i = 0; i < N; i++)
id[i] = i;
}
public boolean connected(int p, int q)
{ return id[p] == id[q]; }
public void union(int p, int q)
{
int pid = id[p];
int qid = id[q];
for (int i = 0; i < id.length; i++)
if (id[i] == pid) id[i] = qid;
}
}
Upvotes: 3