## 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(data[i]>max){
max = data[i];
}
}
return max;
}

//2.计算数组中最小值
public static int arrayMinElement(int[] data){
int min = data[0];
for(int i = 0;i < data.length;i++){
if(data[i] < min){
min = data[i];
}
}
return min;
}

//3.计算数组值之和
public static int arrayElementSum(int[] data){
int sum = 0;
for(int i = 0;i<data.length;i++){
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 j = 0;j<b.length;j++){
c[a.length+j] = b[j];
}
printArray(c);
return c;
}

//5.数组截取
//[start, end)
public static int[] arraySub(int[] data, int start , int end){
if ((start<0)||(end<0)||((end-start)>data.length)|| (start > end)){
System.out.println("出错");
return null;
}
int[] b = new int[end-start];
for(int i = start;i<end;i++){
b[i-start] = data[i];
}
printArray(b);
return b ;
}

//6.数组打印
public static void printArray(int[] data){
for(int i = 0;i<data.length;i++){
System.out.print(data[i]+" ");
}
System.out.print("\n");
}

//7.数组反转
// 比如：[1,2,3,4] => [4,3,2,1]
public static void printReversal(int[] data){
int left = 0;
int right = data.length-1;
while(left<right){
int temp = data[left];
data[left] = data[right];
data[right] = temp;
left++;
right--;
}
printArray(data);
}

public static void main(String[] args){
int[] a =new int[]{1,2,3,4,5};
int[] b = new int[]{2,4,6,8,0};
System.out.println("数组中的最大值:"+arrayMaxElement(a));
System.out.println("数组中的最小值:"+arrayMinElement(a));
System.out.println("数组之和:"+arrayElementSum(a));
System.out.println("数组拼接:"+arrayJoin(a,b));
System.out.println("数组截取:"+arraySub(a,2,4));
printReversal(a);

}
}``````

0条评论