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);
}
}