[英]How to generate 100 random 3 digit numbers in java?
我需要生成100個隨機的3位數字。 我已經弄清楚了如何生成1個3位數字。 我如何產生100? 到目前為止,這就是我所擁有的...
import java.util.Random;
public class TheNumbers {
public static void main(String[] args) {
System.out.println("The following is a list of 100 random" +
" 3 digit numbers.");
Random rand= new Random();
int pick = rand.nextInt(900) + 100;
System.out.println(pick);
}
}
基本概念是使用for-next
循環,您可以在其中重復所需次數的計算...
您應該查看The for Statement以獲得更多詳細信息
Random rnd = new Random(System.currentTimeMillis());
for (int index = 0; index < 100; index++) {
System.out.println(rnd.nextInt(900) + 100);
}
現在,這不會排除生成重復項的可能性。 您可以使用Set
來確保值的唯一性...
Set<Integer> numbers = new HashSet<>(100);
while (numbers.size() < 100) {
numbers.add(rnd.nextInt(900) + 100);
}
for (Integer num : numbers) {
System.out.println(num);
}
嘗試循環
for(int i=0;i<100;i++)
{
int pick = rand.nextInt(900) + 100;
System.out.println(pick);
}
如果您將以下代碼適應您的問題
for(int i= 100 ; i < 1000 ; i++) {
System.out.println("This line is printed 900 times.");
}
,它將做您想要的。
使用問題的答案使用Java生成一定范圍內的隨機數 :
import java.util.Random;
public class TheNumbers {
public static void main(String[] args) {
System.out.println("The following is a list of 100 random 3 digit nums.");
Random rand = new Random();
for(int i = 1; i <= 100; i++) {
int randomNum = rand.nextInt((999 - 100) + 1) + 100;
System.out.println(randomNum);
}
}
如果3位數字包括以0開頭的數字(例如,如果您正在生成PIN碼),例如000、011、003等,則此解決方案是一種替代方法。
Set<String> codes = new HashSet<>(100);
Random rand = new Random();
while (codes.size() < 100)
{
StringBuilder code = new StringBuilder();
code.append(rand.nextInt(10));
code.append(rand.nextInt(10));
code.append(rand.nextInt(10));
codes.add(code.toString());
}
for (String code : codes)
{
System.out.println(code);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.