1 import java.util.Scanner; //首先導入Scanner類包 2 public class six3{ 3 public static void main(String[]args){ 4 int a[]=new int[5]; //創建一個數組,且分配好內存。 5 int x,min,max; 6 System.out.println("please input numbers"); 7 Scanner s=new Scanner(System.in); //從鍵盤輸入 8 for(x=0;x<5;x++) 9 a[x]=s.nextInt(); //利用循環給數組初始化 10 min=max=a[0]; //把最大值和最小值都給初始為數組第一個元素 11 for( x=0;x<5;x++){ 12 if(a[x]>max) 13 max=a[x]; //用循環把最大值和數組中每個元素作比較 14 if(min>a[x]) 15 min=a[x];} //把最小值和數組每個元素作比較 16 System.out.println("數組中的最大值為:"+max); 17 System.out.println("數組中的最小值為:"+min); 18 } 19 }
運行結果: