-2

I'm trying to call a non static method from the main method. all of these are in the same class, I know that if the method i am calling isnt static the program yields an error. How can i call the methods from the main without changing them to static?

public class BinSearch {
   public static void main(String[] args){
      createArray();

   }

   //creates an array
   public int[] createArray(){
   .....
   }
}
cee
  • 9
  • 2
  • 7

3 Answers3

2

Instantiate an object of the class in which that method belongs and you'll be able call that method. Like this:

public class BinSearch {
    public static void main(String[] args){
        BinSearch myObj = new BinSearch();
        int[] a = myObj.createArray();
}
burglarhobbit
  • 1,860
  • 2
  • 17
  • 32
1

You need to create an instance of BinSearch

(new BinSearch()).createArray();
0
public class BinSearch {
   public static void main(String[] args){
      BinSearch bs = new BinSearch();
      bs.createArray();

   }

   //creates an array
   public int[] createArray(){
   .....
   }
}
Jonah Graham
  • 7,890
  • 23
  • 55