day05--.数组作为方法返回值_返回地址
This commit is contained in:
@@ -0,0 +1,90 @@
|
|||||||
|
package com.inmind.array01;
|
||||||
|
/*
|
||||||
|
数组作为方法返回值_返回地址
|
||||||
|
*/
|
||||||
|
public class Demo09 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
int[] arr = {1,2,3,4,5,6,7};
|
||||||
|
//1.打印原数组
|
||||||
|
printArr(arr);
|
||||||
|
System.out.println("-------------------");
|
||||||
|
//2.调用获取偶数新数组的方法
|
||||||
|
int[] newArr = getOsArray(arr);
|
||||||
|
//3.打印新数组
|
||||||
|
//创建相同长度的数组,只获取偶数保存返回 [2,4,6]
|
||||||
|
printArr(newArr);
|
||||||
|
}
|
||||||
|
//定义一个方法,传入一个数组,将数组中的偶数,封装起来,并将只含有偶数的新数组返回回来
|
||||||
|
public static int[] getOsArray(int[] arr) {
|
||||||
|
//先获取偶数的数量
|
||||||
|
int osCount = getOsCount(arr);
|
||||||
|
|
||||||
|
//动态初始化一个偶数的数量长度整数数组
|
||||||
|
int[] newArr = new int[osCount];
|
||||||
|
int index = 0;//对新数组的索引,手动管理
|
||||||
|
|
||||||
|
//遍历判断是偶数则保存到新数组中
|
||||||
|
for (int i = 0; i < arr.length; i++) {
|
||||||
|
int temp = arr[i];//遍历时,每个元素
|
||||||
|
if (temp % 2 == 0) {
|
||||||
|
newArr[index++] = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return newArr;
|
||||||
|
}
|
||||||
|
|
||||||
|
//定义一个获取整数数组中偶数的数量
|
||||||
|
public static int getOsCount(int[] arr) {
|
||||||
|
int count = 0;
|
||||||
|
for (int i = 0; i < arr.length; i++) {
|
||||||
|
int temp = arr[i];
|
||||||
|
if (temp % 2 == 0) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//方式二
|
||||||
|
public static int[] getOsArray2(int[] arr) {
|
||||||
|
//动态初始化一个整数数组
|
||||||
|
int[] newArr = new int[arr.length];
|
||||||
|
int index = 0;//对新数组的索引,手动管理
|
||||||
|
|
||||||
|
//遍历判断是偶数则保存到新数组中
|
||||||
|
for (int i = 0; i < arr.length; i++) {
|
||||||
|
int temp = arr[i];//遍历时,每个元素
|
||||||
|
if (temp % 2 == 0) {
|
||||||
|
newArr[index++] = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static void printArr(int[] arr){
|
||||||
|
for (int i = 0; i < arr.length; i++) {
|
||||||
|
System.out.print(arr[i]+"-");
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user