2015-11-20 18 views
-1

我需要生成一個介於0和9999之間的隨機數,然後我需要將這些數字全部四個字符長 - 因此,如果1238生成的很好,但如果96產生需要顯示0096,或3將是0003如何製作一個長度爲4個字符的隨機數 - Java

這是到目前爲止我的代碼...

public static void main(String[] args) { 
    Random randomGenerator = new Random(); 

    for (int i = 0; i < 5; i = i++) { 
     int randomInteger = randomGenerator.nextInt(9999); 
     System.out.println(randomInteger); 
    } 

} 

}

+4

'的System.out。 printf(「%04d」,randomInteger);' – lurker

+0

謝謝!我也需要這樣做,所以它不使用1111,2222,3333,4444等9999如何做到這一點? – Demi

+1

你的問題根本就沒有提到。您能否更新您的問題(使用[編輯](http://stackoverflow.com/posts/33827593/e​​dit)鏈接)以清楚地解釋您的所有要求?例如,你想要什麼和什麼之間的隨機數字?你想避免什麼樣的數字? – lurker

回答

1
String.format("%04d", randomInteger) 
+2

請避免'toString()'。 '%04d'需要一個整數。 –

+0

謝謝,修復它。 – BetaRide

2

您可以使用String.format()這樣做。你的情況,你可以做

System.out.println(String.format("%04d",randomInteger)); 
0

以上所有的答案是正確的,但如果你真的不想使用字符串格式化功能,你可以試試下面的代碼

public static void main(String[] args) { 
     int min = 1000;  
     int max = 9999; 
     Random r = new Random(); 
     for (int i = 0; i < 5; i = i++) { 
      randomInteger = r.nextInt(max - min + 1) + min; 
      System.out.println(randomInteger); 
     } 
    } 
+0

該解決方案如何產生OP給出的例子「0003」或「0096」? – lurker

相關問題