0

I code in Python normally, this error makes no sense to me. I can't fathom what I could be doing wrong here. I checked out similar threads with same error message to no avail.

I think this error has something to do with the same classes and methods are called in Java. Tried switching around the way method is called but didn't do it. Any ideas?

public class test2 {


    public int[] makeMiddle(int[] nums){

        int[] l1 = {nums[(nums.length/2)-1], nums[(nums.length/2)]};
        return l1;

    }

    public static void main(String[] args){
        makeMiddle({1,2,3,4});
        makeMiddle({5,6,2,1,7,6,3,4,0,1});
    }   

}
chopper draw lion4
  • 12,401
  • 13
  • 53
  • 100

3 Answers3

2

You have a couple of problems with your code.

public int[] makeMiddle(int[] nums){

    int[] l1 = {nums[(nums.length/2)-1], nums[(nums.length/2)]};
    return l1;

}

main is a static function. This means that it can be called without actually instantiating an object of that class. Static functions cannot reference any member variables (because it is not guaranteed that those variables have been instantiated), and thus can only call member functions that are marked as static. Change your method definition to this:

public static int[] makeMiddle(int[] nums){

You also have a syntax error (repeated twice).

makeMiddle({1,2,3,4});
makeMiddle({5,6,2,1,7,6,3,4,0,1});

Should be

makeMiddle(new int[]{1,2,3,4});
makeMiddle(new int[]{5,6,2,1,7,6,3,4,0,1});  
casperw
  • 320
  • 1
  • 6
  • So, if I understand correcltly; 1) If main is static then it can only call static methods, and 2) I need to type casts even parameters in Java – chopper draw lion4 Mar 30 '14 at 17:42
  • 1
    @chopperdrawlion4 1) main can call non-static methods, provided you provide it with the object to call them on, such as in @dafi's answer. 2) You can eliminate the `new int[] {` ... `}` if you set makeMiddle's parameter type to `int...`, as in my answer. – Boann Mar 30 '14 at 17:48
  • 1
    Main is always required to be static. If you want to call non-static methods of an object, you have to instantiate that object in main and then use it to call its methods. – casperw Mar 30 '14 at 17:48
1

You must use the construct new int[] {a,b, ...};

public static void main(String[] args){
    test2 t2 = new test2();
    t2.makeMiddle(new int[]{1,2,3,4});
    t2.makeMiddle(new int[]{5,6,2,1,7,6,3,4,0,1});
}   
dafi
  • 3,492
  • 2
  • 28
  • 51
1

If you change the type of makeMiddle's parameter from int[] to int..., then you can call it very simply as follows:

makeMiddle(1,2,3,4);

You can still also call it with an explicit array, such as:

makeMiddle(new int[] { 1,2,3,4 });

The method should also be static, as it is called from static main.

Boann
  • 48,794
  • 16
  • 117
  • 146