数组学习的几个案例

<span style="font-family: Helvetica, "Hiragino Sans GB", 微软雅黑, "Microsoft YaHei UI", SimSun, SimHei, arial, sans-serif; background-color: rgb(255, 255, 255);">
</span>
<span style="font-family: Helvetica, "Hiragino Sans GB", 微软雅黑, "Microsoft YaHei UI", SimSun, SimHei, arial, sans-serif; background-color: rgb(255, 255, 255);">1.</span><span style="font-family: Helvetica, "Hiragino Sans GB", 微软雅黑, "Microsoft YaHei UI", SimSun, SimHei, arial, sans-serif; line-height: 1.6; widows: auto; background-color: rgb(255, 255, 255);"><span style="color:#ff0000;">数组获取最值(获取数组中的最大值最小值)</span></span>
分析:
A:定义一个数组,并对数组的元素进行静态初始化。
B:从数组中任意的找一个元素作为参照物(一般取第一个),默认它就是最大值。
C:然后遍历其他的元素,依次获取和参照物进行比较,如果大就留下来,如果小,就离开。
D:最后参照物里面保存的就是最大值。
class ArrayTest2 {
	public static void main(String[] args) {
		//定义一个数组
		int[] arr = {34,98,10,25,67};
		
		//请获取数组中的最大值
		/*
		//从数组中任意的找一个元素作为参照物
		int max = arr[0];
		//然后遍历其他的元素
		for(int x=1; x<arr.length; x++) {
			//依次获取和参照物进行比较,如果大就留下来,如果小,就离开。
			if(arr[x] > max) {
				max = arr[x];
			}
		}
		//最后参照物里面保存的就是最大值。
		System.out.println("max:"+max);
		*/
	
		//把这个代码用方法改进
		//调用方法
		int max = getMax(arr);
		System.out.println("max:"+max);
			
		//请获取数组中的最小值
		int min = getMin(arr);
		System.out.println("min:"+min);
	}
	
	/*
		需求:获取数组中的最大值
		两个明确:
			返回值类型:int
			参数列表:int[] arr
	*/
	public static int getMax(int[] arr) {
		//从数组中任意的找一个元素作为参照物
		int max = arr[0];
		//然后遍历其他的元素
		for(int x=1; x<arr.length; x++) {
			//依次获取和参照物进行比较,如果大就留下来,如果小,就离开。
			if(arr[x] > max) {
				max = arr[x];
			}
		}
		//最后参照物里面保存的就是最大值。
		return max;
	}
	
	public static int getMin(int[] arr) {
		//从数组中任意的找一个元素作为参照物
		int min = arr[0];
		//然后遍历其他的元素
		for(int x=1; x<arr.length; x++) {
			//依次获取和参照物进行比较,如果小就留下来,如果大,就离开。
			if(arr[x] < min) {
				min = arr[x];
			}
		}
		//最后参照物里面保存的就是最小值。
		return min;
	}
}
2.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值