views:

48

answers:

2

I am trying to get a function in JAVA to take a value in an array as input. Here is my attempt:

public static void main(String[]args)
{
    int [] a = new int [4];
    a[0]=6;
    a[1]=7;
    a[2]=5;
    a[3]=2;
    int g = 11;
    System.out.println calc(a[0], 11);
}
public static int calc(a[], int g)

I am doing this before running a recursion. However, I keep getting an error message. What is the correct way to do this? I want the function, however, to an input from an array. How do I get the function to take not just any int value but rather from the row of a given array?

+2  A: 

Change this:

public static int calc(a[], int g)

To this:

public static int calc(int value, int g)

When you do System.out.println(calc(a[0], 11)); you're actually passing an int to function calc. That int resides in the first position a[0] of the array.

If you want to pass the whole array to calc, your function signature must be:

public static int calc(int[] a, int g)

You'd call it this way:

System.out.println(calc(a, 11));

This line System.out.println calc(a[0], 11); in your code is also wrong. It should be:

System.out.println(calc(a[0], 11));

Suppose your calc function has this:

public static int calc(int value, int g)
{
    return value + g;
}

When you call:

System.out.println(calc(a[0], 11));

The output will be:

17

Why 17? Because you're summing a[0] = 6 + 11 = 17.

a[0] is a row of the array and you're actually passing it to the function calc.

In the recursive case, you could have and indexer i for example.

for(int i = 0; i < a.length; i++)
{
     // You could check some condition here:
     // if(a[i] > 10) { System.out.println(calc(a[i+1], 11)); }
     System.out.println(calc(a[i], 11));
}

Now when you execute this code you'll have this output:

17
18
16
13
Leniel Macaferi
I want the function, however, to an input from an array. How do I get the function to take not just any int value but rather from the row of a given array?
Spencer
That's just what I showed you. See the updated answer.
Leniel Macaferi
I know, but I eventually want to write a recursive function. So I want it start at a[0] and if that condition is not met, move to a[1] etc. Therefore I want calc to take as input values from the array a
Spencer
See the updated answer. Is that what you're trying to do?
Leniel Macaferi
A: 

If you want to call the method as it is, ie, with an array as the first parameter, then you have to pass the array in when you call it.

Instead of:

System.out.println(calc(a[0], 11));

Do:

System.out.println(calc(a, 11));

This will pass the entire array as input, rather than the value at position 0 in the array.

Nader Shirazie