简体   繁体   中英

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. 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 ...

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 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. 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.

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