ในการแบ่งอิลิเมนต์คู่และคี่ออกเป็นสองรายการ โค้ด 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 ในอาร์เรย์คู่หรือคี่