Java 程式,將偶數和奇數元素拆分為兩個不同的列表
要將偶數和奇數元素拆分為兩個不同的列表,Java 程式碼如下所示 −
示例
import java.util.Scanner;
public class Demo{
public static void main(String[] args){
int n, j = 0, k = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of elements required :");
n = s.nextInt();
int my_arr[] = new int[n];
int odd_vals[] = new int[n];
int even_vals[] = new int[n];
System.out.println("Enter the elements of the array(even and add numbers) :");
for(int i = 0; i < n; i++){
my_arr[i] = s.nextInt();
}
for(int i = 0; i < n; i++){
if(my_arr[i] % 2 != 0){
odd_vals[j] = my_arr[i];
j++;
} else {
even_vals[k] = my_arr[i];
k++;
}
}
System.out.print("The odd numbers in the array : ");
if(j > 1){
for(int i = 0;i < (j-1); i++){
if(odd_vals[i]==1){
System.out.println("1 is niether even nor odd");
}
else
System.out.print(odd_vals[i]+",");
}
System.out.print(odd_vals[j-1]);
} else {
System.out.println("There are no odd numbers.");
}
System.out.println("");
System.out.print("The even numbers in the array : ");
if(k > 1){
for(int i = 0; i < (k-1); i++){
if(even_vals[i]==1){
System.out.println("1 is niether even nor odd");
}
else
System.out.print(even_vals[i]+",");
}
System.out.print(even_vals[k-1]);
} else {
System.out.println("There are no even numbers in the array.");
}
}
}輸出
Enter the number of elements required : Enter the elements of the array(even and add numbers) : The odd numbers in the array : 1 is niether even nor odd 9 The even numbers in the array : 2,4,6
控制檯輸入
5 1 2 4 6 9
一個名為‘Demo’的類包含主函式,該函式詢問要在陣列中儲存的元素數量,並宣告兩個新陣列,分別儲存奇數值和偶數值。陣列元素取自使用者,並執行一個‘for’迴圈來檢查數字是否能被 0 整除,即檢查當數字除以 2 時的餘數是否為 0。如果符合要求,則主陣列中的那個數字將儲存在偶數陣列中,否則儲存在奇數陣列中。由於 1 既不是偶數也不是奇數,因此它在偶數或奇數陣列中儲存 1 的同時列印訊息。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP