0
Can someone give an example and explain how arrays work with methods... Thanx
3 Respuestas
+ 2
Do you mean, you don't know how to pass an array as a parameter in a method?
Let's say we want write a method, in which you pass an int-array, and that returns the average value of this array.
public class Program
{
//here's the method with an int-array (int[]) as a parameter, a double-array would work as well
private static double average(int[] array)
{
//sum up all the elements of the array and then divide through its length
double avg = 0.0;
for(int i=0; i< array.length; ++i)
{
avg += array[i];
}
avg/= array.length;
return avg;
}
public static void main(String[] args)
{
// create a new array
int[] myArray = new int[]{1,3,5,7};
// call the method
double avg = average(myArray);
// output the result
System.out.println("The Average of the array is: " + avg);
}
}
You can also return an Array as the return value of a method!
example:
//this is amethod returning an array which elements are within a range of numbers
private static int[] getRangeArray(int from, int to, int step)
{
//if step is 0 return an empty array
if(step == 0)
return new int[0];
//step is always positive
step = step<0? -step : step;
//calculate the size of the array
int size = (to-from)/step;
size = size<0? -size : size;
++size;
//create the array with the size
int[] array = new int[size];
int c = 0;
//if from is smaller (equal) than to, count up
if(from <= to)
{
for(int i = from; i<= to; i+=step)
{
array[c++] = i;
}
}
//else count down
else
{
for(int i = from; i>=to; i-=step)
{
array[c++] = i;
}
}
return array;
}
0
in Java
0
thx lulugo