简体   繁体   中英

Error when Calling a Java Method

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.

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;
    }
}

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM