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