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?
Change this:
To this:
When you do
System.out.println(calc(a[0], 11));you’re actually passing anintto functioncalc. Thatintresides in the first positiona[0]of the array.If you want to pass the whole array to
calc, your function signature must be:You’d call it this way:
This line
System.out.println calc(a[0], 11);in your code is also wrong. It should be:Suppose your
calcfunction has this:When you call:
The output will be:
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 functioncalc.In the recursive case, you could have and indexer
ifor example.Now when you execute this code you’ll have this output: