如何在Java中移除数组中的偶数?
在Java中,数组是一个对象。它是一种非原始数据类型,用于存储相同数据类型的多个值。
根据题意,我们需要删除或消除数组中存在的偶数,并打印奇数数组。
注意 - 数组必须是整数数组。
如果一个数字能被2整除,则称其为偶数。
在本文中,您将了解如何使用Java编程语言从数组中移除偶数。让我们一起探索。
一些示例
示例1
Suppose the original array is {2, 5, 16, 14, 31, 22, 19, 20}
执行操作后,即移除偶数后,更新后的数组为:[5, 31, 19]
示例2
Suppose the original array is {12, 15, 16, 14, 31, 22, 9, 21}
执行操作后,即移除偶数后,更新后的数组为:[15, 31, 9, 21]
示例3
Suppose the original array is {12, 15, 16, 17}
执行操作后,即移除偶数后,更新后的数组为:[15, 17]
算法
步骤1 - 声明并初始化一个整数数组。
步骤2 - 声明for循环并检查奇数元素。
步骤3 - 将奇数元素存储到一个新数组中。
步骤4 - 打印数组的元素。
语法
要获取数组的长度(数组中元素的数量),数组有一个内置属性,即length
以下是其语法:
array.length
其中,“array”指的是数组引用。
多种方法
我们提供了不同的方法来解决这个问题。
使用静态数组初始化
使用用户自定义方法
让我们逐一查看程序及其输出。
方法1:使用静态数组初始化
示例
在这种方法中,数组元素将在程序中初始化。然后,根据算法从Java中的数组中移除偶数。
import java.util.*;
public class Main{
//main method
public static void main(String[] args){
// variables
int countOdd = 0;
int odd[] = null;
//declared and initialized an array
int numbers[] = {12, 5 , 77, 14, 91, 21, 1, 50};
// count odd numbers
for (int i : numbers){
if (!(i % 2 == 0))
++countOdd;
}
// create array to store odd numbers
odd = new int[countOdd];
// check each element and insert
int i = 0;
for (int num : numbers) {
if (!(num % 2 == 0)) {
// odd
odd[i++] = num;
}
}
//print odd array
System.out.println("Array after removing even numbers are: ");
System.out.println(Arrays.toString(odd));
}
}
输出
Array after removing even numbers are: [5, 77, 91, 21, 1]
方法2:使用用户自定义方法
示例
在这种方法中,数组元素将在程序中初始化。然后,通过将数组作为参数传递给用户自定义方法,并在方法内部根据算法从Java数组中移除偶数。
import java.util.*;
public class Main{
//main method
public static void main(String[] args){
//declared and initialized an array
int numbers[] = { 44, 5 , 9, 15, 31, 22, 19, 48 };
//calling the user defined method
removeEven(numbers);
}
//user defined method to remove even numbers
public static void removeEven(int []numbers){
// variables
int countOdd = 0;
int odd[] = null;
// count odd numbers
for (int i : numbers){
if (!(i % 2 == 0))
++countOdd;
}
// create array to store ood numbers
odd = new int[countOdd];
// check each element and insert
int i = 0;
for (int num : numbers) {
if (!(num % 2 == 0)) {
// even
odd[i++] = num;
}
}
//print even array
System.out.println("Array after removing even numbers are: ");
System.out.println(Arrays.toString(odd));
}
}
输出
Array after removing even numbers are: [5, 9, 15, 31, 19]
在本文中,我们探讨了如何使用Java编程语言从数组中移除偶数。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP