簡體   English   中英

如何在Java中排除隨機數中的數字

[英]How to exclude number in random number in Java

因此,我將獲得一個介於1到9999之間的隨機數,但是我想排除1111、3333、4444、7777,而while循環是否有用?

Random r = new Random();

int x = r.nextInt(9999);

while (x == 1111 || x==3333){
    x = r.nextInt(9999) + 1;
} 

您的解決方案很好。 您也可以使用do-while循環。 這樣它將首先生成一個隨機數,然后進行檢查。

Random rnd = new Random();
int x=0;
do{
    x = rnd.nextInt(9999)+1;
}while(x==1111 || x==3333 || x==4444 || x==7777);

是的,在這種情況下, while表示它將繼續處理新的隨機數,直到它與您的代碼中的1111或3333不同為止。

您的代碼沒有錯,只有小事。

1-固定您的時間來滿足您的條件:

while (x == 1111 || x == 3333 || x == 4444 || x == 7777)

2-方法nextInt處理從0(含)到給定數字(如Javadocs所聲明的那樣)的隨機數(感謝@ user3437460):

返回從此隨機數生成器的序列得出的偽隨機數,其均勻分布的{@code int}值介於0(含)和指定值(不含)之間。

所以:

Random r = new Random();
int x = r.nextInt(9999)+1;
while (x == 1111 || x == 3333 || x == 4444 || x == 7777) {
    x = r.nextInt(9999) + 1;
}
System.out.println(x);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM