day05-数组作为方法返回值_返回地址
This commit is contained in:
79
day05/src/com/inmind/array01/Demo09.java
Normal file
79
day05/src/com/inmind/array01/Demo09.java
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
package com.inmind.array01;
|
||||||
|
/*
|
||||||
|
数组作为方法返回值类型_返回地址
|
||||||
|
*/
|
||||||
|
public class Demo09 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
//根据一个整数数组,定义一个方法,将数组中的偶数,提出来组成新的数组返回
|
||||||
|
int[] arr = {10, 34, 5, 6, 72, 8, 75, 98};
|
||||||
|
//调用方法,获取新的数组,遍历展示数组中内容
|
||||||
|
int[] newArr = getOsArray3(arr);
|
||||||
|
//新数组的正向遍历
|
||||||
|
for (int i = 0; i < newArr.length; i++) {
|
||||||
|
System.out.print(newArr[i]+" ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//获取偶数数组方式三
|
||||||
|
public static int[] getOsArray3(int[] arr){
|
||||||
|
//自定义一个索引,来对原始的数据进行索引的维护
|
||||||
|
int index = 0;
|
||||||
|
//新的数组的长度应该就是偶数的个数!!!
|
||||||
|
int count = 0;//统计原数组中偶数的个数
|
||||||
|
for (int i = 0; i < arr.length; i++) {
|
||||||
|
if (arr[i] % 2 == 0) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] newArr = new int[count];
|
||||||
|
for (int i = 0; i < arr.length; i++) {
|
||||||
|
//获取每个元素
|
||||||
|
int temp = arr[i];
|
||||||
|
//判断是否是偶数,是则保存到新数组
|
||||||
|
if (temp % 2 == 0) {
|
||||||
|
newArr[index] = temp;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return newArr;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//获取偶数数组方式二
|
||||||
|
public static int[] getOsArray2(int[] arr){
|
||||||
|
//自定义一个索引,来对原始的数据进行索引的维护
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//定义一个方法,将数组中的偶数,提出来组成新的数组返回
|
||||||
|
//获取偶数数组方式一
|
||||||
|
public static int[] getOsArray1(int[] arr){
|
||||||
|
//创建一个新的与原数组长度一样的数组,遍历原数组,判断是偶数,就相应的保存到新数组中
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user