2015-12-22 68 views
-6
package com.nusecond.Code; 
import java.util.*; 

public class Code { 

    public static void main(String args[]){ 

     Random random=new Random(); 
     for(int j=10;j<=99;j++){   
      int num=random.nextInt(100) ; 
      //ssLong i=System.currentTimeMillis(); 
      //String result = String.format("%04d", i % 10000); 
      System.out.println("Code generated:" +num); 
     } 
    } 
} 

我想在10和99隨機數發生器兩位數

注意打印兩位數的隨機數:我想我每次運行程序時只有一個號碼。

+0

運行程序時的一個數字意味着什麼? –

+2

「我只需要一個號碼」爲什麼你有一個從10到99的循環?這將給你89個數字介於0和99之間。 – Arc676

+0

可能的重複[在Java範圍內生成隨機整數](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range- with-java) –

回答

0

您可以使用此方法:

private static int showRandomInteger(int aStart, int aEnd, Random aRandom){ 
    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 * aRandom.nextDouble()); 
    int randomNumber = (int)(fraction + aStart);  
    return randomNumber; 
} 

的參數,你必須通過這種方法是:

  • aStart:你的初始值(即10,你的情況下)
  • aEnd :你的結局值(即你的情況爲99)
  • aRandom:這將是的一個對象(Random random=new Random();
3

隨機數字,如果您需要從某個數字開始,只需將該隨機數字添加到該下限。傳遞給隨機數的上限將是上限減去下限。

int num = random.nextInt(90) + 10; 
0

Random random = new Random();

//產生從10到90的隨機整數,即2位隨機數。

int abc = 10+random.nextInt(90);