Even 및 Odd 요소를 두 개의 다른 목록으로 분할하기 위해 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을 저장하면서 메시지를 출력합니다.