如何在Java中移除陣列中的偶數?


在Java中,陣列是一個物件。它是一種非原始資料型別,用於儲存相同資料型別的多個值。

根據題意,我們需要刪除或消除陣列中存在的偶數,並列印奇數陣列。

注意 - 陣列必須是整數陣列。

如果一個數字能被2整除,則稱其為偶數。

在本文中,您將瞭解如何使用Java程式語言從陣列中移除偶數。讓我們一起探索。

一些示例

示例1

Suppose the original array is {2, 5, 16, 14, 31, 22, 19, 20}

執行操作後,即移除偶數後,更新後的陣列為:[5, 31, 19]

示例2

Suppose the original array is {12, 15, 16, 14, 31, 22, 9, 21}

執行操作後,即移除偶數後,更新後的陣列為:[15, 31, 9, 21]

示例3

Suppose the original array is {12, 15, 16, 17}

執行操作後,即移除偶數後,更新後的陣列為:[15, 17]

演算法

  • 步驟1 - 宣告並初始化一個整數陣列。

  • 步驟2 - 宣告for迴圈並檢查奇數元素。

  • 步驟3 - 將奇數元素儲存到一個新陣列中。

  • 步驟4 - 列印陣列的元素。

語法

要獲取陣列的長度(陣列中元素的數量),陣列有一個內建屬性,即length

以下是其語法:

array.length

其中,“array”指的是陣列引用。

多種方法

我們提供了不同的方法來解決這個問題。

  • 使用靜態陣列初始化

  • 使用使用者自定義方法

讓我們逐一檢視程式及其輸出。

方法1:使用靜態陣列初始化

示例

在這種方法中,陣列元素將在程式中初始化。然後,根據演算法從Java中的陣列中移除偶數。

import java.util.*;
public class Main{

   //main method
   public static void main(String[] args){
   
      // variables
      int countOdd = 0;
      int odd[] = null;
      
      //declared and initialized an array
      int numbers[] = {12, 5 , 77, 14, 91, 21, 1, 50};
      
      // count odd numbers
      for (int i : numbers){
         if (!(i % 2 == 0))
         ++countOdd;
      }

      // create array to store odd numbers
      odd = new int[countOdd];
    
      // check each element and insert
      int i = 0;
      for (int num : numbers) {
         if (!(num % 2 == 0)) { 
            // odd
            odd[i++] = num;
         }
      }
      
      //print odd array
      System.out.println("Array after removing even numbers are: ");
      System.out.println(Arrays.toString(odd));
   }
}

輸出

Array after removing even numbers are: 
[5, 77, 91, 21, 1]

方法2:使用使用者自定義方法

示例

在這種方法中,陣列元素將在程式中初始化。然後,透過將陣列作為引數傳遞給使用者自定義方法,並在方法內部根據演算法從Java陣列中移除偶數。

import java.util.*;
public class Main{

   //main method
   public static void main(String[] args){
   
      //declared and initialized an array
      int numbers[] = { 44, 5 , 9, 15, 31, 22, 19, 48 };
      
      //calling the user defined method
      removeEven(numbers);    
   }
   
   //user defined method to remove even numbers 
   public static void removeEven(int []numbers){
   
      // variables
      int countOdd = 0;
      int odd[] = null;
      
      // count odd numbers
      for (int i : numbers){
         if (!(i % 2 == 0))
         ++countOdd;
      }
      
      // create array to store ood numbers
      odd = new int[countOdd];
      
      // check each element and insert
      int i = 0;
      for (int num : numbers) {
         if (!(num % 2 == 0)) { 
            // even
            odd[i++] = num;
         }
      }
      
      //print even array
      System.out.println("Array after removing even numbers are: ");
      System.out.println(Arrays.toString(odd));
   }
}

輸出

Array after removing even numbers are: 
[5, 9, 15, 31, 19]

在本文中,我們探討了如何使用Java程式語言從陣列中移除偶數。

更新於:2023年1月5日

4K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.