Home > Blockchain >  Java: Invalid Method Declaration
Java: Invalid Method Declaration

Time:03-19

Im trying to call the method getCollumAverages to test it out but i cant seem to get it to work due to the errors in the picture below. This method is outside main()

    /*
        3. Convert number 1 to a method called getColumAverages that takes in a two dimensional
           array of integers as parameter and returns a one dimensional array of numbers
           Test this method with the array you created in number 2.
    */ 
  int [] [] grades = {{100, 99, 98}, {97, 96, 95}, {94, 93, 92}, {91, 90, 90}};
  public int[] getCollumAverages(int [] [] Array)
  {
    int sum = 0;
    int [] colAvg = new int [Array[0].length];
    for(int col = 0; col < Array[col].length; col  )
    {
      for(int row = 0; row < Array.length; row  )
      {
       sum  = Array[row][col];
      }
      colAvg[col] = sum / Array.length;
      sum = 0;
    }
    return colAvg;
  }
  
getCollumAverages(grades); //error on this line

Image of error

CodePudding user response:

You have to call the getCollumAverages() method in the main method. You are calling the method outside of a method and therefore java thinks that your method call is you trying to define a method. Next thing is once you put the method call in main(), you will get another error that you can't call a non-static method from within a static method (main). Therefore you will need to make the method getCollumAverages() static.

CodePudding user response:

Just call the function in another one:

Solution :

    int [] [] grades = {{100, 99, 98}, {97, 96, 95}, {94, 93, 92}, {91, 90, 90}};
    public void main() {
        getCollumAverages(grades); //no error on this line
    }
        
    public int[] getCollumAverages(int [] [] Array){
        int sum = 0;
        int [] colAvg = new int [Array[0].length];
        for(int col = 0; col < Array[col].length; col  )
        {
          for(int row = 0; row < Array.length; row  )
          {
           sum  = Array[row][col];
          }
          colAvg[col] = sum / Array.length;
          sum = 0;
        }
        return colAvg;
    }

CodePudding user response:

You are not storing the return of the method. Try:

int[] result = getCollumAverages(grades);
  • Related