目录
案例一:数组最大值的索引
需求:定义一个方法,找到数组中最大值的索引
代码:
package cn.itcast.method;
public class Test10 {
public static void main(String[] args) {
int[] arr1 = {12, 55, 11, 54, 8, 41, 21, 88, 41, 2};
int count = max(arr1);
System.out.println(count);
}
//定义最大值方法
public static int max(int[] arr) {
int max = arr[0]; //定义第一个元素为最大往后面比较
int index = 0; //记录索引的编号
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
index = i;
}
}
//返回值
return index;
}
}
运行:
案例二:找出数组中的奇数并打印
需求:定义一个方法
1.定义方法,将老数组中的奇数放入新数组。
2.先得到奇数的个数,用来动态定义新数组的长度。
3.创建新的数组,将arr1中的奇数保存。
4.遍历老数组将奇数放入新数组。
5.调用打印输出。
代码:
package cn.itcast.method;
public class Test13 {
public static void main(String[] args) {
int[] arr1 = {1,2,3,45,69,32,14,45,8};
//调用方法
int[] arr2 = method(arr1);
//遍历新数组
for (int i = 0; i < arr2.length; i++) {
System.out.println(arr2[i]);
}
}
//定义方法,将老数组中的奇数放入新数组
public static int[] method(int[] arr1){
//0.先得到奇数的个数,用来动态定义新数组的长度
int count = 0;
for (int i = 0; i < arr1.length; i++) {
if (arr1[i]%2==1){
count++;
}
}
//1.创建新的数组,将arr1中的奇数保存
int[] arr2 = new int[count];
int index = 0;
//2.遍历老数组将奇数放入新数组
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] % 2 ==1){
arr2[index] = arr1[i];
index++;
}
}
//将新数组返回
return arr2;
}
}
运行:
案例三:反转数组
需求:定义一个方法,反转数组。
package cn.itcast.method;
/*
定义一个方法,反转数组
*/
public class Test14 {
public static void main(String[] args) {
int[] arr1 = {10, 20, 30, 40, 50};
//调用方法
int[] arr2 = method(arr1);
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i] + " ");
}
}
public static int[] method(int[] arr) {
//定义两个变量保存用来左边和右边调换位置
int left = 0;
int right = arr.length - 1;
while (left < right) { //第一个和最后一个换位置
int temp = arr[left];//第二个和倒数第二个换位置
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return arr;
}
}
运行: