Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java tách phần tử chẵn lẻ thành hai danh sách khác nhau


Để tách phần tử chẵn lẻ thành hai danh sách khác nhau, mã Java như sau:

Ví dụ

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.");       }    } }

Kết quả

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

Đầu vào console

5 1 2 4 6 9

Lớp Demo chứa main hỏi số phần tử lưu trong mảng, khai báo hai mảng mới lưu giá trị lẻ và chẵn. Phần tử mảng lấy từ người dùng, vòng for kiểm tra số chia hết cho 2 dư 0. Nếu có, lưu vào mảng chẵn, ngược lại mảng lẻ. Vì 1 không chẵn cũng không lẻ, in thông báo khi lưu 1 vào mảng chẵn hoặc lẻ.