day05-数组作为参数或返回值的练习
This commit is contained in:
21
day05/src/com/inmind/Demo05.java
Normal file
21
day05/src/com/inmind/Demo05.java
Normal file
@@ -0,0 +1,21 @@
|
||||
package com.inmind;
|
||||
/*
|
||||
数组作为方法参数_传递地址
|
||||
*/
|
||||
public class Demo05 {
|
||||
public static void main(String[] args) {
|
||||
//定义int型数组
|
||||
int[] arr = {1,2,3};
|
||||
foreachArray(arr);
|
||||
//定义int型数组
|
||||
int[] arr1 = {4,5,6};
|
||||
foreachArray(arr1);
|
||||
}
|
||||
|
||||
//我要定义一个方法,动态接收int数组,对该数组进行遍历打印
|
||||
public static void foreachArray(int[] array){
|
||||
for (int i = 0; i < array.length; i++) {
|
||||
System.out.println(array[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
79
day05/src/com/inmind/Demo06.java
Normal file
79
day05/src/com/inmind/Demo06.java
Normal file
@@ -0,0 +1,79 @@
|
||||
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]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user