简体   繁体   中英

How do I cast an array of doubles into an array of integers in Java?

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();
}

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 int s to an int array ( int[] ) and return it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM