java数组
//Java数组章节练习题
public class ArrayUtils{
//1.计算数组中最大值
public static int arrayMaxElement(int[] data){
int max=data[0];
for(int i=1;i<data.length;i++){
if (max<data[i])
max=data[i];
}
return max;
}
//2.计算数组中最小值
public static int arrayMinElement(int[] data){
int min=data[0];
for(int i=1;i<data.length;i++){
if (min>data[i])
min=data[i];
}
return min;
}
//3.计算数组值之和
public static int arrayElementSum(int[] data){
int sum=data[0];
for(int i=1;i<data.length;i++){
sum=sum+data[i];
}
return sum;
}
//4.数组拼接
public static int[] arrayJoin(int[] a, int[] b){
int [] c=new int[a.length+b.length];
for(int i=0;i<a.length;i++){
c[i]=a[i];
}
for(int i=a.length;i<c.length;i++){
c[i]=b[i-a.length];
}
return c;
}
//5.数组截取
//[start, end)
public static int[] arraySub(int[] data, int start , int end){
if(end<start){
System.out.println("区间非法");
return null;
}
int[] a=new int[end-start+1];
if(start>=data.length||start<0){
System.out.println("起始越界");
}
if(end>data.length){
end=data.length;
}
for(int i=start;i<end;i++){
a[i]=data[i];
}
return a;
}
//6.数组打印
public static void printArray(int[] data){
for(int i=0;i<data.length;i++){
System.out.print(data[i]+" ");
}
System.out.println();
}
//7.数组反转
// 比如:[1,2,3,4] => [4,3,2,1]
public static void printReversal(int[] data){
int left=0,right=data.length-1,temp;
while(left<=right){
temp=data[left];
data[left]=data[right];
data[right]=temp;
left++;
right--;
}
}
public static void main(String[] args){
int []data={3,5,9,4,7,10,6,17};
int []a={1,2,3,4};
int []b={5,6,7,8};
int max=arrayMaxElement(data);
System.out.println(max);
int min=arrayMinElement(data);
System.out.println(min);
int sum =arrayElementSum(data);
System.out.println(sum);
int []c=arrayJoin(a,b);
for(int i=0;i<c.length;i++){
System.out.print(c[i]+" ");
}
System.out.println();
int[] a1=arraySub(data,0,2);
for(int i=0;i<2;i++){
System.out.print(a1[i]+" ");
}
System.out.println();
printReversal(data);
printArray(data);
}
}
输出结果: