-1

I would like to print a number in the main() method which is the result returned from method foo(). What should I do? Am I missing something? I'm just exercising programming by making different pseudo-codes into an actual thing or well, functional...

This is the whole program, that I'm working on:

public class programB {

     /* PSEUDO CODE:
     * 
     * foo(A)
       n ← A.length
       x ← A[1]
       for i ← 2 to n do
       if A[i] > x then
       x = A[i]
       return x
                 */

    int array [] = {3,4,1,2,5};

    static int foo(int[] array){
        int n = 5;
        int x = array[1];

        for(int i = 2; i <= n; i++){
            if(array[i] > x){
                x = array[i];
            }
        }
        return x;
    }

    public static void main(String[] arguments){
        foo();
    }
}

This is the error, that I'm getting:

Error: The method foo(int[]) in the type programB is not applicable for the arguments ()

Something about the method's arguments not being applicable...
Can someone please help me out here?

Abra
  • 19,142
  • 7
  • 29
  • 41
  • 2
    This error can be reworded as: The method foo(int[]) must b called by passing an int array as argument, but you're not passing anything. – JB Nizet Oct 26 '19 at 19:32
  • `foo(array);` and arrays start at `0` (not `1`). Also, `array` must be `static` to access from `main`. And `array[5]` will be an out of bounds, use `array.length` (and `<` not `<=`, because arrays start at `0`). – Elliott Frisch Oct 26 '19 at 19:32
  • If you're trying to just find the max element, then see https://stackoverflow.com/questions/1484347/finding-the-max-min-value-in-an-array-of-primitives-using-java – OneCricketeer Oct 26 '19 at 19:40
  • Spoiler: After you resolve the _not applicable for the arguments_ error, you will get a `ArrayIndexOutOfBoundsException`. (Don't say I didn't warn you :-) – Abra Oct 26 '19 at 19:44
  • Thanks everyone! I've just completed the whole program, it runs just fine now. – 45LongColt Oct 26 '19 at 21:16

1 Answers1

0

make your array static

static int array [] = {3,4,1,2,5};

call it in the main method.

public static void main(String[] arguments){
        foo(array);
    }
sakirow
  • 189
  • 1
  • 5
  • 18
  • It worked! I just had to put the 'static' prefix in front of the array initialization sentence. I also had to change the <= operator in the 'for' loop to the < operator only, as Elliott Frisch stated above.Thank you! – 45LongColt Oct 26 '19 at 21:26