Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java แยกตัวเลขคู่และคี่เป็น List แยกกัน

ตัวอย่างโค้ด

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 odd 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 neither 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 neither 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 : 5
Enter the elements of the array (even and odd numbers) : 1 2 4 6 9
The odd numbers in the array : 1 is neither even nor odd 9
The even numbers in the array : 2,4,6

คลาส Demo มี main function รับจำนวน elements จากผู้ใช้ สร้างอาร์เรย์หลักและอาร์เรย์แยกสำหรับเลขคู่/คี่ วนลูปรับค่าเข้าไป แล้ววนลูปตรวจสอบหาร 2 ลงตัวหรือไม่ (mod 2) แยกเก็บในอาร์เรย์ที่เหมาะสม พิจารณาเลข 1 ว่าไม่ใช่คู่也不คี่ แสดงผลแยกกัน