JAVA——计算数组的最大值,最小值,数组值的和,数组合并,数组截取

1,计算数组的最大值
2,计算数组的最小值
3,计算数组和
4,合并数组
5,截取数组

 public class ArrayEvent{

 //1,计算数组中的最大值
 public static int arrMax(int[] arr1){
  if(arr1 == null){
  //IllegalArgumentException 参数异常
  //如果arr1 == null时,发生异常,提示"arr1 must be not null.
            throw new IllegalArgumentException("arr1 must be not null.");   
  }
  int max = Integer.MIN_VALUE;//将max先定为最小值
  for(int i = 0;i < arr1.length;i++){
   if(arr1[i] > max){
    max = arr1[i];
   }
  }
  return max;
 }


 //2,计算数组中的最小值
 public static int arrMin(int[] arr1){
  if(arr1 == null){
            throw new IllegalArgumentException("arr1 must be not null.");
  }
  int min = Integer.MAX_VALUE;
  for(int i = 0;i < arr1.length;i++){
   if(arr1[i] < min){
    min = arr1[i];
   }
  }
  return min;
 }


 //3,计算数组值之和
 public static int arrSum(int[] arr1){
  if(arr1 == null){
            throw new IllegalArgumentException("arr1 must be not null.");
  }
  int sum = 0;
  for(int i = 0;i < arr1.length;i++){
   sum = sum + arr1[i];
  }
  return sum;
 }


 //4,数组拼接
 public static int[] arrJoin(int[] arr1,int[] arr2){
  if(arr1 == null){
            throw new IllegalArgumentException("arr1 must be not null.");
  }
  if(arr2 == null){
            throw new IllegalArgumentException("arr2 must be not null.");
  }
  int arr3[] = new int[arr1.length+arr2.length];
  for(int i = 0;i < arr1.length;i++){
   arr3[i] = arr1[i];
  }
  for(int i = arr1.length;i < arr3.length;i++){
   arr3[i] = arr2[i - arr1.length];
  }
  return arr3;
 }


 //5,数组截取
 public static int[] arrCut(int[] arr1,int start,int end){
  if(arr1 == null){
            throw new IllegalArgumentException("arr1 must be not null.");
  }
  if(start < 0 || end < 0){
   throw new IllegalArgumentException("start or end must be not < 0");
  }
  if(end < start){
   throw new IllegalArgumentException("end must be not < start");
  }
  if(start >= arr1.length){
   throw new IllegalArgumentException("start must be < arr1.length");
  }
  if(end >= arr1.length){
   throw new IllegalArgumentException("end must be < arr1.length");
  }
  //是否end也不能大于等于arr1.length
  int count = end - start;
  int[] arr3 = new int[count];
  for(int i = 0; i < count;i++){
   arr3[i] = arr1[start+i];
  }
  return arr3;
 }
 public static void printArray(int[] arr){
  for(int i = 0;i < arr.length;i++){
   System.out.print(arr[i]+"\t");
  }
  System.out.println();
 }
 public static void main(String[] args){
  int[] arr1 = new int[]{11,2,45,67,8,90};
  int[] arr2 = new int[]{1,2,3};
  System.out.println(arrMax(arr1));
  System.out.println(arrMin(arr1));
  System.out.println(arrSum(arr1));
  int[] join = arrJoin(arr1,arr2);
  printArray(join);
  int[] cut = arrCut(arr1,0,6);
  printArray(cut);
 }
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值