So I will get a random number between 1 to 9999, but I want to exclude 1111, 3333, 4444, 7777 and is that use while loop?
Random r = new Random();
int x = r.nextInt(9999);
while (x == 1111 || x==3333){
x = r.nextInt(9999) + 1;
}
So I will get a random number between 1 to 9999, but I want to exclude 1111, 3333, 4444, 7777 and is that use while loop?
Random r = new Random();
int x = r.nextInt(9999);
while (x == 1111 || x==3333){
x = r.nextInt(9999) + 1;
}
Your solution is fine. You may also use a do-while loop. So that it will generate a random number first, then check.
Random rnd = new Random();
int x=0;
do{
x = rnd.nextInt(9999)+1;
}while(x==1111 || x==3333 || x==4444 || x==7777);
Yes, in this case the while
means that it will continue to process a new random number until it is different from 1111 or 3333 on your code.
There is nothing wrong with your code, only minor things.
1 - Fix your while to attend your condition:
while (x == 1111 || x == 3333 || x == 4444 || x == 7777)
2 - The method nextInt
process a random number from 0 (inclusive) to the given number exclusive as the Javadocs states (thanks to @user3437460):
Returns a pseudorandom, uniformly distributed {@code int} value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
So:
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);