简体   繁体   English

使用 if 查找和计算数组中的奇数

[英]Find and count odd numbers in a array with using an if

So i´ve been tryng to count the odd numbers in an array without the help of an if.所以我一直在尝试在没有 if 帮助的情况下计算数组中的奇数。 Any Master coders out there (i am a novice).那里的任何主编码器(我是新手)。

public static void main(String[] args) {


      int array[] = {1,4,5,9,0,-1,5,7};
      int count = 0;
        for (int i = 0; i <array.length ; i++) {
            if (array[i] %2 != 0){
                count ++;
            }
        }

        System.out.println("Odds " + count);

}

Even better, not even a for needed ;)更好的是,甚至不需要 ;)

public static void main(String[] args) {
        int array[] = { 1, 4, 5, 9, 0, -1, 5, 7 };
        long count = Arrays.stream(array).filter(it -> (it & 1) == 1).count();
        System.out.println("Odds " + count);
    }

Okay all you need to do is build the int array into a String using StringBuilder ...好了,所有你需要做的是建立在int数组到一个String使用StringBuilder ...

Then you need to split it into two arrays by evens and odds!然后你需要把它按偶数和几率分成两个数组! Now you have an array of evens and an array odds!现在你有一个偶数数组和一个赔率数组! As Strings!作为字符串! You find the number of odds by taking the length of the array after.您可以通过获取数组的长度来找到赔率的数量。 You also can then parse them back into int or leave them as String and just print them:然后,您还可以将它们解析回int或将它们保留为String并打印它们:

      int array[] = {1,4,5,9,0,-1,5,7};

      StringBuilder sb = new StringBuilder();

        for (int i = 0; i <array.length ; i++) 
        {
            sb.append(array[i]);
            sb.append(",");
        }
        String str = sb.toString();

        //You can split and them parse them back into an integer!  And then print them anyway!
        String[] odds = str.split("\\,*\\-*\\s*[24680]*\\,");
        //This is the number of odds!
        System.out.println(odds.length);
        for (String odd : odds) {
            int oddNum = Integer.parseInt(odd);
            System.out.print(oddNum + " ");
        }

        System.out.println();

        //Or just print them!
        String[] evens = str.split("\\,*\\-*\\s*[13579]*\\,");
        for (String even : evens) {
            System.out.print(even + " ");
        }

Note: My regex is not the best and this can be improved to remove whitespace/empty characters better注意:我的正则表达式不是最好的,这可以改进以更好地删除空格/空字符

PS.附注。 No if statements were harmed in the making of this code.没有if语句在编写此代码时受到损害。 Also this code is clearly not meant to be use in a real setting, and I did it mess around with regex but it does what was required.此外,这段代码显然不打算在真实环境中使用,我把它弄乱了正则表达式,但它做了所需的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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