簡體   English   中英

使用 if 查找和計算數組中的奇數

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

所以我一直在嘗試在沒有 if 幫助的情況下計算數組中的奇數。 那里的任何主編碼器(我是新手)。

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

}

更好的是,甚至不需要 ;)

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

好了,所有你需要做的是建立在int數組到一個String使用StringBuilder ...

然后你需要把它按偶數和幾率分成兩個數組! 現在你有一個偶數數組和一個賠率數組! 作為字符串! 您可以通過獲取數組的長度來找到賠率的數量。 然后,您還可以將它們解析回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 + " ");
        }

注意:我的正則表達式不是最好的,這可以改進以更好地刪除空格/空字符

附注。 沒有if語句在編寫此代碼時受到損害。 此外,這段代碼顯然不打算在真實環境中使用,我把它弄亂了正則表達式,但它做了所需的工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM