This is my homework question: "Create a method called roundAllUp()
, which takes in an array of doubles and returns a new array of integers. This returned array contains all the numbers from the array of doubles, but rounded up."
Here is the method I have so far:
public static int[] roundUp(double[] array2){
for(int i = 0; i < array2.length; i++){
Math.ceil(array2[i]);
}
}
Once the values are rounded up from the array of doubles, how can I return them in an array of integers?
You're close, you need to create a new array of int
(s) and assign the result of your Math.ceil
calls (with an appropriate cast). Like,
public static int[] roundUp(double[] array2) {
int[] arr = new int[array2.length];
for (int i = 0; i < array2.length; i++) {
arr[i] = (int) Math.ceil(array2[i]);
}
return arr;
}
If you're using Java 8+, you could also use a DoubleStream
and map each element to an int
before converting to an array in one line. Like,
public static int[] roundUp2(double[] array2) {
return DoubleStream.of(array2).mapToInt(d -> (int) Math.ceil(d)).toArray();
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments