Nido Al Saher
Nido Al Saher

Reputation: 25

Cannot call instance method from static method

I have this class and I just need help with the toString() inside the methods to actually show the result. It gives me an error that I can't use getName() or getId() in a static context :

public static void bubbleSort(Student[] array)
{
    for(int i=(array.length); i>0; i--)
        for(int j=1; j<(array.length-i); j++)
            if(array[j].getName().compareTo(
               array[j+1].getName())<0) {
                Student Temp = array[j];
                array[j] = array[j+1];
                array[j+1] = Temp;
            }

    String s = null;
    for (int i=0; i<array.length; i++) {
    // the error is here under the getName and getId 
        s= s+ getName()+" "+ getId() ;
    } 
    System.out.print (s);
}

Upvotes: 0

Views: 651

Answers (3)

user1610015
user1610015

Reputation: 6668

You probably want array[i].getName() and array[i].getId() instead of just getName() and getId().

Upvotes: 0

nkr
nkr

Reputation: 3058

I think you want to print the names and IDs of the Students you previously sorted.

public static void bubbleSort(Student[] array)
{
    for(int i=(array.length); i>0; i--)
    {

        for(int j=1; j<(array.length-i); j++) 
        {
             if( array[j].getName().compareTo(array[j+1].getName())<0)

            {
                Student Temp = array[j];
                array[j] = array[j+1];
                array[j+1] = Temp;
            }

        }
    }

    String s = ""; // should not be null

    for (int i = 0; i < array.length; i++)
    {
        s = s + array[i].getName()+" "+ array[i].getId(); // changed this line
        System.out.print (s); // moved this into the loop because I think this makes more sense
    }
}

The methods getName() and getID() belong to the object Student and are not methods of the class where bubbleSort() is defined.

Upvotes: 1

Frank
Frank

Reputation: 15641

instead of:

s= s+ getName()+" "+ getId() ;

you probably need to do this:

s= s+ array[i].getName()+" "+ array[i].getId() ;

and as said in the comment above use:

String s = "";

Upvotes: 1

Related Questions