1. 程式人生 > >Java陣列的應用2:陣列的最大,最小,求和,平均值,倒置

Java陣列的應用2:陣列的最大,最小,求和,平均值,倒置

import java.util.Scanner;

public class HelloWorld {
	public static void main(String[] args){
	//	Scanner s = new Scanner(System.in);
	//	System.out.println("請輸入一個數字");
	//	int num = s.nextInt();
		Scanner s = new Scanner(System.in);
		int sum = 0 ; //存放陣列的和
		int []a = new int[6] ;
		for(int i = 0 ; i < a.length ; i++){
			System.out.println("請輸入陣列的第"+(i+1)) ;
			a[i] = s.nextInt();
			sum += a[i];
		}
		//求最大值和最小值
		int max = a[0] , min = a[0];
		for(int i = 1 ;i < a.length ; i++){
			if(max < a[i])
				max = a[i];
			if(min > a[i])
				min = a[i];
		}
		//求陣列的平均值
		int avg = sum / a.length ;
		
		for(int i = 0 ; i < a.length ; i++){
			System.out.println(a[i]) ;
		}
		System.out.println("最大值:"+max+"最小值"+min+"平均值"+avg);
		//實現陣列倒置
		for(int i = 0 ; i <= a.length / 2 - 1; i++){
			int t = a[i];
			a[i] = a[a.length - i - 1] ;
			a[a.length-i-1] = t;
		}
		for(int i = 0 ; i < a.length ; i++){
			System.out.println(a[i]) ;
		}
	}
}