public class ArrayUtils{ //创建类(数组工具类)
//1.计算数组中最大值
public static int arrayMaxElement(int [] data){ //创建方法
if(data == null){ //如果数组为空
//IllegalArgumentException 参数异常
throw new IllegalArgumentException("data must be not null.");
} //抛出异常
int max = Integer.MIN_VALUE; //初始max为默认最小值
for(int i=0; i<data.length; i++){
if(data[i]>max){ //for循环遍历数组 如果大于max将这个数赋给max
max=data[i];
}
}
return max;
}
//2.计算数组中最小值
public static int arrayMinElement(int [] data){
if(data == null){
throw new IllegalArgumentException("data must be not null.");
}
int min = Integer.MAX_VALUE;
for(int i=0; i<data.length; i++){
if(data[i]<min){
min=data[i];
}
}
return min;
}
//3.计算数组值之和
public static int arrayElementSum(int [] data){
if(data == null){
throw new IllegalArgumentException("data must be not null.");
}
int sum = 0;
for(int i=0; i<data.length; i++){
sum=sum+data[i];
}
return sum;
}
//4.数组拼接
public static int[] arrayJoin(int[] a, int[] b){
if(a ==null){
throw new IllegalArgumentException("a must be not null.");
} //数组ab为空时抛出异常
if(b == null){
throw new IllegalArgumentException("b must be not null.");
}
int len = a.length+b.length; //计算拼接后的数组c的长度
int[] c= new int[len]; //初始化c
for(int i=0; i<a.length; i++){
c[i]=a[i]; //先将a数组全部放在c中
}
for(int i=a.length; i<c.length;i++){
c[i]=b[i-a.length]; //将b数组从第零个放在c后面
}
return c;
}
//5.数组截取
//[start, end)
public static int[] arraySub(int[] a, int start , int end){
if(a==null){
throw new IllegalArgumentException("a must be not null.");
}
if(start < 0 || end < 0){
throw new IllegalArgumentException("start or end must be > 0.");
}
if(end < start){
throw new IllegalArgumentException("end > start.");
}
if(start>=a.length){
throw new IllegalArgumentException("start must be < a.length .");
}
//各种异常下 抛出异常 使代码比较健壮 不容易有bug
int count = end-start; //计算截取后数组的长度
if(count>a.length){
throw new IllegalArgumentException("sub length must be <= a.length .");
}
int[] b = new int[count]; //初始化b
for(int i=start ; i< end ;i++){
b[i-start]=a[i]; //从a的start到end 赋值给新数组b
}
return b;
}
public static void printArray(int [] a){
if(a == null){
return;
}
for(int i=0; i< a.length; i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
public static void main(String[] args){
int[] a = new int[]{23,12,43,51,21};
int max = arrayMaxElement(a);
System.out.println(max);//51
int[] sub = arraySub(a,0,5);
printArray(sub);
}
}
初学Java:计算数组中最大值 ---计算数组中最小值----计算数组之和----实现两个数组----拼接数组截取
猜你喜欢
转载自blog.csdn.net/qq_43223415/article/details/83821091
今日推荐
周排行