-3
public class Makakiesmarkou {

void swap(int i, int j, int[] arr) {
    int t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;
}

public void MySort(int[] T)
{
    for(int m=0; m<T.length-1; m++)
    {
        int j=m;
        for(int k=m+1; m<T.length-1; k++)
        {
            if(T[k]<T[j])
                j=k;
        }
        swap(T[j], T[m], T);
    }
}

public static void main(String[] args) {

    int[] pin= new int[50];
    MySort(pin);
    System.out.println(Arrays.toString(pin));
}

}

the error when i call MySort in the main class is "non static method MySort[int[]] cannot be referenced from a static context"

what am i doing wrong?

Constantine
  • 763
  • 2
  • 9
  • 19

2 Answers2

1

You can either do what Salah said, or you can instantiate your class and call MySort on that:

public static void main(String[] args) {

    int[] pin= new int[50];
    Makakiesmarkou m = new Makakiesmarkou();
    m.MySort(pin);
    System.out.println(Arrays.toString(pin));
}
gla3dr
  • 2,179
  • 16
  • 29
  • i get, what does this mean? Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50 at makakiesmarkou.Makakiesmarkou.MySort(Makakiesmarkou.java:25) at makakiesmarkou.Makakiesmarkou.main(Makakiesmarkou.java:36) Java Result: 1 – Constantine Apr 08 '14 at 19:14
  • @Kostas It might be because you are passing the wrong thing to your swap method. You are passing the _values_ in the array that you want to swap instead of the _indices_ of the values you want to swap. Your swap method doesn't care what the values are it is swapping, it only cares where they are in the array. – gla3dr Apr 08 '14 at 19:21
0

You need to change the declaration of your method to be static like:

public static void MySort(int[] T)

static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance().

So if you try to access a non static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance. So in my opinion only reason which make sense to disallow non static or instance variable inside static context is non existence of instance.

Read more here

Salah
  • 8,567
  • 3
  • 26
  • 43