1. 程式人生 > >Java陣列章節練習

Java陣列章節練習

1.計算陣列中最大值  2.計算陣列中最小值  3.計算陣列值之和  4.陣列拼接  5.陣列拼接  6.陣列列印  7.陣列反轉

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];
			 }
		 }
        System.out.println(max);
    }
    
    //2.計算陣列中最小值
    public static int arrayMinElement(int[] data){
		int main = data[0];
		for(int i = 1; i < data.length; i++){
			if(data[i] < min){
				min = data[i];
			}
		}
        System.out.println(min);;
    }
    
    
    //3.計算陣列值之和
    public static int arrayElementSum(int[] data){
		int sum = data[0];
		for(int i = 1; i < data.length; i++){
			sum = sum + data[i];
		}
        System.out.println(sum);;
    }
    
    //4.陣列拼接
    public static int[] arrayJoin(int[] a, int[] b){
		int[] c = new int[a.length + b.length];
		for(int i = 1; i < a.length; i++){
			c[i] = a[i];
			System.out.print(c[i]+" ");
		}
		for(i = a.length; i < c.length; i++){
			c[i] = b[i - a.length];
			System.out.print(c[i]+" ");
		}
    }

    //5.陣列拼接
    //[start, end)
    public static int[] arraySub(int[] data, int start , int end){
		if(end < start){
			System.out.println("非法始末");
		}
		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];
			System.out.print(a[i]+" ");
		}
    }
    
    //6.陣列列印
    public static void printArray(int[] data){
		for(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;
		int right = data.length;
		int tmp = 0;
	
	    while(left <= right){
			tmp = data[left];
			data[left] = data[right];
			data[right] = tmp;
			left++;
			right--;
		}
    }
	
	
     // 測試  
    public static void main(String[] args){
		int[] a = {1,2,3,4};
		int[] b = {5,6,7,8};
		int[] data = {20,21,22,23,25};
		
		//max
		arrayMaxElement(a);
		arrayMaxElement(b);
		arrayMaxElement(data);
		System.out.println();
		
		//min
		arrayMinElement(a);
		arrayMinElement(b);
        arrayMinElement(data);	
        System.out.println();
		
		//sum
		arrayElementSum(a);
		arrayElementSum(b);
		arrayElementSum(data);
		System.out.println();
		
		//陣列拼接
		arrayJoin(a,b);
		System.out.println();
		
		//陣列擷取
		arraySub(data,1,3);
		System.out.println();
		
		//陣列列印
		printArray(data);
		System.out.println();
		
		//陣列反轉
		printReversal(a);
		printArray(a);
		System.out.println();
    }
}