2010-01-16 33 views
2

我只是想知道如何使用J2ME CLDC 1.0 MIDP 2.0生成隨機數?J2ME:如何生成隨機數?

基本上我想在每次從手機屏幕點擊菜單項 Generate時生成一個14位數的隨機數。

+0

我使用CLDC 1.0 MIDP 2.0 – Sarfraz 2010-01-16 16:22:29

回答

2

我不是很熟悉J2ME,但是Javadoc表明Random類是CLDC API的一部分,因此您可以產生這樣一個14位數:

public static void main(String[] args) { 
    Random r = new Random(); 
    long l = r.nextLong(); 
    System.out.println(String.format("%015d", l).substring(1, 15)); 
} 
+0

我認爲這樣會更少隨機...兩個隨機長可以有相同的前14個字符,而不是等於。 – 2010-01-16 11:42:43

+0

比什麼隨機性更少? – 2010-01-16 11:49:28

+2

如果你做了相反的事情,它只會是「較少隨機」,即嘗試從一個超過10^14個可能值的來源生成一個14位數的數字。上面的代碼有一個不同的問題:當隨機長度小於14位時,會導致StringIndexOutOfBoundsException。 – 2010-01-16 11:51:38

1

可以使用Random類MIDP的,或者一個在CLDC 1.1

你可以做nextLong,然後截斷,或者使用next(44)並從那裏迭代有一個真正的14號長。

+0

14位將溢出int變量。 – jarnbjo 2010-01-16 11:42:34

+0

omg,什麼是newb錯誤:/ 改變它很長 – 2010-01-16 11:50:17

+0

我不相信你打算使用無參數nextInt()方法... – 2010-01-16 11:54:59

0
import java.util.Random; 

private static void showRandomInteger(int aStart, int aEnd){ 
     Random generator = new Random(); 
     generator.setSeed(System.currentTimeMillis()); 
     if (aStart > aEnd) { 
      throw new IllegalArgumentException("Start cannot exceed End."); 
     } 
     //get the range, casting to long to avoid overflow problems 
     long range = (long)aEnd - (long)aStart + 1; 
     // compute a fraction of the range, 0 <= frac < range 
     long fraction = (long)(range * generator.nextDouble()); 
     int randomNumber = (int)(fraction + aStart); 
     System.out.println("Generated : " + randomNumber); 
     } 

你可以使用這種通用方法計算任意範圍內的隨機數。

+0

'nextDouble()'是不是在隨機 – 2010-01-16 12:47:08

+0

的J2ME版本訪問是它不存在在CLDC 1.0,但你可以在CLDC 1.1 – Vivart 2010-01-16 13:35:25

+1

找到,但我使用CLDC 1.0,該怎麼辦? – Sarfraz 2010-01-16 16:23:26

2
Random r = new Random(); 
r.nextInt(bottomX-topX)+topX; //will give you the next random integer in range [bottomX,topX]