java.util.Random 類的 nextInt(int num )

來源:互聯網
上載者:User

標籤:

隨機產生3個67~295的整數並找出數值置中的數 並輸出中間的數
例如:100,225和200,輸出200

要隨機產生某個範圍內的整數,用 java.util.Random 類的 nextInt(int num) 最簡潔。

nextInt( int num) 能接受一個整數作為它所產生的隨機整數的上限,下限為零,比如:
nextInt(4)將產生0,1,2,3這4個數字中的任何一個數字,注意這裡不是0-4,而是0-3。
。但下限總是零,不能更改,所以若要達到非零下限的效果,必須把上限減去下限的結果傳給 nextInt( ),然後把下限加入 nextInt( ) 返回的整數。

把隨機數採集到數組裡,然後用同樣是在 java.util 包裡的 Arrays.sort( ) 做數組排序後,置中數近在眼前。

 1 import java.util.*; 2  3 class C { 4      public static void main( String[ ] args ) { 5  6          Random rand = new Random( ); 7          int[ ] trio = new int[ 3 ]; 8  9          System.out.println( "Three random integers in the range of [67, 295):" );10          for( int i = 0; i < 3; ++i ) {11              trio[ i ] = rand.nextInt( 295 - 67 ) + 67;12              System.out.println( trio[ i ] );13          }14 15          Arrays.sort( trio );16 17          System.out.println( "\nMedian:\n" + trio[ 1 ] );18      }19 }

 

java.util.Random 類的 nextInt(int num )

聯繫我們

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