需求:请使用三元运算符计算出数组的最大值和最小值。
目的:练习数组遍历和三元运算。
分析:
1、定义一个数组。使用静态初始化。
2、数组遍历。
3、三元运算进行判断。
代码实现:
package com.Ethan.Demo01;public class Text1003 { //主方法 public static void main(String[] args) { //定义一个数组变量,使用静态初始化存入数据 int[] arr = {4, 1, 8, 9}; int max = arr[0]; int small = arr[0]; //在数组遍历中使用三元运算进行判断;符合要求即可赋值给对应变量 for (int i = 1; i < arr.length; i++) { max = max > arr[i] ? max : arr[i]; small = small < arr[i] ? small : arr[i]; } //输出结果 System.out.println("该数组最大数字是:" + max); System.out.println("该数组最小数字是:" + small); }}