简体   繁体   中英

Call Method Outside Class

So I am trying to call a method I have in a different class.

It's a simple task, and I have looked at many tutorials and other posts on here, but for some reason I just can't get it to work.

Here is the first class

public class ArrayProcessor {

   public void print3IntArray(int[] array) {
      for (int i = 0; i < 3; i++) {
         System.out.println("Entry " + i + " is " + array[i]);
      }
   }
}

I first tried

import java.util.Random;

public class ArrayProgram {

   public static void main(String[] args) {

   Random rand = new Random();

   int[] anArray = new int[3];

      for(int i = 0; i < 3; i++) {
         int random = rand.nextInt(11);
         anArray[i] = random;
      }
   }
   ArrayProcessor.print3IntArray(anArray);
}

But then after looking at some posts on this website I tried

import java.util.Random;

public class ArrayProgram {

   public static void main(String[] args) {

   ArrayProcessor ap = new ArrayProcessor();

   Random rand = new Random();

   int[] anArray = new int[3];

      for(int i = 0; i < 3; i++) {
         int random = rand.nextInt(11);
         anArray[i] = random;
      }
   }
   ap.print3IntArray(anArray);
}

Both codes give me the following error:

ArrayProgram.java:21: error: <identifier> expected
   ap.print3IntArray(anArray);
                    ^
ArrayProgram.java:21: error: <identifier> expected
   ap.print3IntArray(anArray);
                            ^
2 errors

You are calling this

ap.print3IntArray(anArray);

after the closing curly brace of the main method, so your code actually does not reside in any method or container block of code, which is unacceptable by the compiler. Change

} // closing curly brace of main()
ap.print3IntArray(anArray);

to

    ap.print3IntArray(anArray);
} // closing curly brace of main()

You cannot call ArrayProcessor.print3IntArray(anArray); outside a method (in this case main method) but if you want to call it inside the main method then make the function print3IntArray static in ArrayProcessor class.

public class ArrayProcessor{
    public static void print3IntArray(int[] array) 
      {
       for (int i = 0; i < 3; i++) {
        System.out.println("Entry " + i + " is " + array[i]);
      }   
}

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