第13节方法练习
案例:数组遍历
需求:设计一个方法用于数组遍历,要求遍历的结果是在一行上的。例如:[11,22,33,44,55]
思路:
1、因为要求结果在一行上输出,所以这里需要在学习一个新的输出语句System.out.print("内容");
System.out.println("内容");输出内容并换行
System.out.print("内容");输出内容不换行
System.out.println();起到换行的作用
2、定义一个数组,用静态初始化完成数组元素初始化
3、定义一个方法,用数组遍历通用格式对数组进行遍历
4、用新的输出语句修改遍历操作
5、调用遍历方法
package com.itheima_01; /* 需求:设计一个方法用于数组遍历,要求遍历的结果是在一行上的。例如:[11,22,33,44,55] * */ public class MethodDemo11 { public static void main(String[] args) { int[] arr = {11, 22, 33, 44, 55}; arrNumber(arr); } public static void arrNumber(int[] arr) { System.out.print("["); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); if(i<arr.length-1){ System.out.print(","); } } System.out.print("]"); } }
输出结果:
[11,22,33,44,55]
案例:数组最大值
需求:设计一个方法用于获取数组中元素的最大值,调用方法并输出结果
思路:
1、定义一个数组,用静态初始化完成数组元素初始化
2、定义一个方法,用来获取数组中的最大值
3、调用获取最大值方法,用变量接收返回结果
4、把结果输出在控制台
package com.itheima_01; /* * * 需求:设计一个方法用于获取数组中元素的最大值,调用方法并输出结果 * * */ public class MethodDemo12 { public static void main(String[] args) { int[] arr={10,22,45,18,12,63,8}; int max = getArrMax(arr); System.out.println("Max:"+max); } public static int getArrMax(int[] arr){ int max=0; max=arr[0]; for(int i=1;i<arr.length;i++){ if(max<arr[i]){ max=arr[i]; } } return max; } }

浙公网安备 33010602011771号