根据数字是否为偶数(真)(假)将int []转换为boolean [] [英] Converting int[] to boolean[] in Java based on whether a number is even (true) or not (false)

查看:79
本文介绍了根据数字是否为偶数(真)(假)将int []转换为boolean []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将包含int数据类型的数组转换为包含布尔数据类型的数组. 我的方法必须能够检查该数字是否为偶数,然后将其存储为"true".甚至是假".返回类型必须为布尔数组. 我该怎么做?我写的代码显然不起作用,我也不十分清楚为什么.实际上,我得到的错误是 ArrayIndexOutOfBoundsException:索引12超出长度6的范围(我的原始数组确实有6个元素).有人可以告诉我为什么吗?我正在使用Java 8.

I am trying to convert an array containing int data type to an array containing boolean data type. My method must be able to check whether the number is even or not and then store it as "true" if even or otherwise "false". The return type must a boolean array. How do I do this? The code I wrote apparenty doesn't work and I do not really understand why. Actually the error I get is ArrayIndexOutOfBoundsException: Index 12 out of bounds for length 6 (my original array has indeed 6 elements). Can someone please tell me why? I am using Java 8.

 public static boolean[] evenNumbers ( int[] array){
            boolean[] array1= new boolean[array.length];
            for (int i: array) {
                if(array[i]%2==0){
                    array5[i]=true;
                }
            }
            return array5;
        }

非常感谢!

推荐答案

在您的循环中,i是元素的 value ,而不是元素的 index ,因此可能不是有效的索引.

In your loop, i is the element’s value, not its index, and so is likely to not be a valid index.

将您的 foreach 循环更改为常规的for循环:

Change your foreach loop to a conventional for loop:

boolean[] result = new boolean[array.length];
for (int i = 0; i < array.length; i++)  {
    result[i] = array[i]%2==0;
}
return result;

这篇关于根据数字是否为偶数(真)(假)将int []转换为boolean []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆