2

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?

2 Answers 2

5

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

I believe that simple casting will do the trick at this point: (int) Math.ceil(array2[i]) is the rounded up int representation of array2[i]. From there you just need to assign those ints to an int array (int[]) and return it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.