標籤:round todo ati 程式設計 font package system color put
通過以上兩次學習,做了一次練習。
練習1:輸入10個數,不用排序求出最大值和次最大值。
1 package exercise; 2 import java.util.Scanner; 3 public class Sort { 4 5 public static void main(String[] args) { 6 // TODO 自動產生的方法存根 7 Scanner in = new Scanner(System.in); 8 System.out.println("Please enter 10 numbers and end with a -1 input :"); 9 int input = in.nextInt();10 int[] numbers = new int[10];//定義並建立擁有10 個元素的數組11 int max = 0;12 int sec = 0;13 while(input != -1)//輸入數組14 {15 for(int i = 0;i < numbers.length;i++)16 {17 numbers[i] = input;18 input = in.nextInt();19 //System.out.print(numbers[i] + " ");20 }21 }22 System.out.println("數組中的元素為:");23 for(int element:numbers)//foreach語句輸出數組24 System.out.print(element + " ");25 System.out.print("\n");26 max = numbers[9];27 sec = numbers[8];28 if(numbers[0] > numbers[1])29 {30 max = numbers[0];31 sec = numbers[1];32 }33 else34 {35 max = numbers[1];36 sec = numbers[0];37 }38 for(int i = 2; i < numbers.length;i++)39 {40 if(numbers[i] > max)41 {42 sec = max;43 max = numbers[i];44 }45 else46 {47 if(numbers[i] > sec)48 {49 sec = numbers[i];50 }51 }52 }53 System.out.println("最大數為:" + max + " 其次為:" + sec);54 }55 }
運行結果為:
Please enter 10 numbers and end with a -1 input :
5 20 40 60 85 95 93 71 83 62 -1
數組中的元素為:
5 20 40 60 85 95 93 71 83 62
最大數為:95 其次為:93
Java程式設計基礎 數組 練習