Can some one tell me where the problem is the program fails to compile

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thatos
    New Member
    • Aug 2007
    • 105

    Can some one tell me where the problem is the program fails to compile

    I would like to design a method which when given an array it returns an array which it's elements are from the initial array greater than the average of all numbers in that array;
    the method average(int array[]) works properly here is the problem

    here is that method
    Code:
      public static int[] small(int array[]){
        double s1 = average(array);
        int length = 0;
        
        
        //Finds how many numbers are greater than the average
        for(int j:array){
          if (j > s1){
            length++;
          }
        }    
        int initial = 0;
        int array2[] = new int[length];
        void add(int p){
          array2[initial] = p;
          initial++;
        }
        for (int j:array){
          if (j > s1)
             array2.add(j);        
        }
        return array2;
      }
    Your reply will be appreciated
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    You're trying to define a local method add() in that other method. The compiler
    will and shall protest against that.

    kind regards,

    Jos

    Comment

    • thatos
      New Member
      • Aug 2007
      • 105

      #3
      Yes, do you have any suggestions how can I go about this because I need that method or I won't be able to accomplish my task or can you tell me what to do please .


      Originally posted by JosAH
      You're trying to define a local method add() in that other method. The compiler
      will and shall protest against that.

      kind regards,

      Jos

      Comment

      • BigDaddyLH
        Recognized Expert Top Contributor
        • Dec 2007
        • 1216

        #4
        Originally posted by thatos
        Yes, do you have any suggestions how can I go about this because I need that method or I won't be able to accomplish my task or can you tell me what to do please .
        When you define methods in a class, you define them one after another:

        [CODE=Java]class Example {
        void method1 () {

        }

        void method2() {

        }
        }[/CODE]

        You don't nest their definitions:

        [CODE=Java]class Example {
        void method1 () {
        void method2() {

        }
        }
        }[/CODE]

        Do you know about Sun's Java tutorial? http://java.sun.com/docs/books/tutorial/java/index.html

        Comment

        Working...