Java 基礎一些代碼練習筆記(RandTest)__Java

來源:互聯網
上載者:User
package com.lee;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.Iterator;import java.util.List;import java.util.Set;import java.util.TreeMap;import java.util.Map;import java.util.Random;/** * 隨機產生50個數字(整數),每個數位範圍是[10, * 50],統計每個數字出現的次數以及出現次數最多的數字與它的個數,最後將每個數字及其出現次數列印出來,如果某個數字出現次數為0 * ,則不要列印它。列印時按照數位升序排列 *  *  *  */public class RandTest {public static void main(String[] args){Map map = new TreeMap();   //儲存數字出現的次數(key為數字,value為數字出現的次數)Random random = new Random();for (int i = 0; i < 50; i++){int number = random.nextInt(41) + 10;Integer in = new Integer(number);if(map.get(in) == null){map.put(in, new Integer(1));}else{int value = ((Integer)map.get(in)).intValue();map.put(in, new Integer(value + 1));}}   //計算出現次數最多Collection cols = map.values();Integer maxOccurs = (Integer)Collections.max(cols);Set set = map.entrySet();List list = new ArrayList();  //儲存出現數字最大的數字for (Iterator iter = set.iterator(); iter.hasNext();){Map.Entry entry = (Map.Entry)iter.next();Integer key = (Integer)entry.getKey();Integer value = (Integer)entry.getValue();if(value.intValue() == maxOccurs.intValue()){list.add(key);}System.out.println(key + ":" + value);} System.out.println("出現的最多次數為:" + maxOccurs);System.out.println("這些數字分別是:");for(Iterator iter = list.iterator(); iter.hasNext();){System.out.println(iter.next());}}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.