Files
javaSE251223/day05/src/com/inmind/Demo06.java

80 lines
2.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.inmind;
public class Demo06 {
public static void main(String[] args) {
//定义出一个整数数组
int[] arr = {1,2,4,6,7,8,9,10,11,13,14};
//alt+enter
// int[] newArr = getOuShuArray(arr);
// int[] newArr = getOuShuArray1(arr);
int[] newArr = getOuShuArray2(arr);
foreachArray(newArr);
}
//定义一个方法,传入一个整数数组,将数组中的偶数,封装起来,并将只含有偶数的新数组返回回来
//方式三:先计算出偶数的个数,再自己维护索引
private static int[] getOuShuArray2(int[] arr) {
//先用遍历计算中原数组中偶数的个数
int num = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
num++;
}
}
//创建一个新的长度跟arr数组的长度一致的int数组
int index = 0;
int[] newArr = new int[num];
for (int i = 0; i < arr.length; i++) {
int temp = arr[i];
if (temp % 2 == 0) {
newArr[index] = temp;
index++;
}
}
return newArr;
}
//方式二:自己控制索引
private static int[] getOuShuArray1(int[] arr) {
//创建一个新的长度跟arr数组的长度一致的int数组
int index = 0;
int[] newArr = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
int temp = arr[i];
if (temp % 2 == 0) {
newArr[index] = temp;
index++;
}
}
return newArr;
}
//方式一:不是很好
private static int[] getOuShuArray(int[] arr) {
//创建一个新的长度跟arr数组的长度一致的int数组
int[] newArr = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
//参数中的每个元素
int temp = arr[i];
if (temp % 2 == 0) {
newArr[i] = temp;
}
}
return newArr;
}
//我要定义一个方法动态接收int数组对该数组进行遍历打印
public static void foreachArray(int[] array){
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}