Java程式設計基礎 數組 練習

來源:互聯網
上載者:User

標籤: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程式設計基礎 數組 練習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.