列印Java中奇數位置存在的陣列元素
在Java中,陣列是一個物件。它是一種非基本資料型別,用於儲存相同資料型別的多個值。
根據題意,我們需要找到陣列中位於奇數位置的元素並列印它們。
如果一個數字能被2整除,則稱其為偶數;否則,稱其為奇數。
注意 − 陣列必須是整數陣列。
讓我們一起學習如何使用Java程式語言來實現這一點。
一些示例
示例1
Suppose the original array is {12, 5, 77, 14, 91, 21, 1, 50}
找到陣列中奇數位置的元素後,結果將是:
Odd position of elements present in an array are: [5, 14, 21, 50]
示例2
Suppose the original array is {12, 23, 11, 64, 5, 87, 22, 67, 100};
找到陣列中奇數位置的元素後,結果將是:
Odd position of elements present in an array are: [23, 64, 87, 67]
示例3
Suppose the original array is {11, 22, 33, 44, 55}
找到陣列中奇數位置的元素後,結果將是:
Odd position of elements present in an array are: [22, 44]
演算法
步驟1 − 宣告並初始化一個整數陣列。
步驟2 − 初始化for迴圈並檢查其長度。
步驟3 − 從索引1開始迴圈,每次增加2,直到陣列的最後一個索引。
步驟4 − 列印陣列的元素。
語法
要獲取陣列的長度(陣列中元素的個數),可以使用陣列的內建屬性 `length`。
以下是其語法:
array.length
其中,`array` 指的是陣列引用。
多種方法
我們提供了多種解決方法。
使用靜態陣列初始化
使用使用者自定義方法
讓我們逐一檢視程式及其輸出。
方法一:使用靜態陣列初始化
示例
在這種方法中,陣列元素將在程式中初始化。然後,根據演算法,我們需要找到陣列中位於奇數位置的元素並列印它們。
public class Main{ //main method public static void main(String[] args){ //Declare and initialize the array elements int num[] = {12, 5 , 77, 14, 91, 21, 1}; System.out.println("Odd position of elements present in an array are: "); //logic implementation for (int i = 1; i < num.length; i = i+2){ System.out.print(num[i]+" "); } } }
輸出
Odd position of elements present in an array are: 5 14 21
方法二:使用使用者自定義方法
示例
在這種方法中,陣列元素將在程式中初始化。然後,透過將陣列作為引數呼叫使用者自定義方法,並在方法內部根據演算法找到並列印陣列中位於奇數位置的元素。
public class Main{ //main method public static void main(String[] args){ int num[] = {12, 23, 11, 64, 5, 87, 22, 67, 100}; // calling the user defined method odd_elements(num); } //method body public static void odd_elements(int []num){ System.out.println("Odd position of elements present in an array are: "); //logic implementation for (int i = 1; i < num.length; i = i+2){ System.out.print(num[i]+" "); } } }
輸出
Odd position of elements present in an array are: 23 64 87 67
在這篇文章中,我們學習瞭如何使用Java程式語言列印陣列中位於奇數索引位置的元素。
廣告