Arrays as parameter/return (declare)
public static type name(type[] name) {
public static type[] name(parameters) {
-
Arrays can be passed as parameters and returned from methods.
-
This method takes an array of
double
s, and returns a new array of rounded int
s:
public static int[] roundAll(double[] realNums) {
int[] roundedNums = new int[realNums.length];
for (int i = 0; i < realNums.length; i++) {
roundedNums[i] = (int) Math.round(realNums[i]);
}
return roundedNums;
}
Arrays as parameter/return (call)
-
Below is an example usage of the
roundAll
method from the previous slide:
import java.util.*; // to use Arrays
public class MyProgram {
public static void main(String[] args) {
double[] realNumbers = {5.5, 7.31, 8.09, -3.234234, 2.0, 0.0};
int[] roundedNumbers = roundAll(realNumbers);
System.out.println(Arrays.toString(roundedNumbers));
}
...
}