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

随机产生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( "
Median:
" + trio[ 1 ] );
18      }
19 }
原文地址:https://www.cnblogs.com/xs-yqz/p/4556106.html