Pantelis10
Pantelis10

Reputation: 15

Passing an array of objects to a method in java

Hello guys I have a question. I have an error when I am trying to pass an array of object to a method My class

public class Object {
     private int x1;

    public Object(int a ,){
            this.x1=a;
     }

public class staticMethods{
    public static void findMaxPos(Object[] name){
             max = name[0]
             pos = 0
            for( int i=1; i<name.length ; i++){
                 if ( name[i] >max ){
                     max = name[i];
                     pos = i;
                     }
              }
      }
public class Example{

public static void main(String[] args) {
Object[] yp = new Object2[3];
    yp[0] = new Object(5);
    yp[1] = new Object(6);
    yp[2] = new Object(8); 
 findMaxPos(type)// i get an error of the  method findMaxPos is undefined for the type Example
   }

So sorry for the long post ...

Upvotes: 0

Views: 14169

Answers (2)

Ayush Trivedi
Ayush Trivedi

Reputation: 1

Well, the above solution should work but apart from that, there are a couple of other things that need to be taken into consideration.

  1. public Object(int a,) Constructor is incomplete.
  2. semicolon(;) is missing in max = name[0], pos = 0
  3. Most importantly the return type of max and Pos is undefined. POs can be int but the variable max should be of the type Object.
  4. If the return type of max is object you can't use (name[i] >max ) as it is undefined for object type. Rectify these mistakes hopefully your code will run fine.

Upvotes: 0

Arnaud
Arnaud

Reputation: 3741

findMaxPos is a static method of your class staticMethod.

When you are not calling a static function inside the class where it is defined, you need to call it with the name of the class before:

public static void main(String[] args) {
    Object[] type = new Object2[3];
    yp[0] = new Object(5);
    yp[1] = new Object(6);
    yp[2] = new Object(8); 
    staticMethods.findMaxPos(type);// This should be ok.
}

Note that in java, the convention is to give classes a name which begin with an uppercase letter (Names which begin with a lowercase letters are given to instances).

Upvotes: 1

Related Questions