0

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;
} 
metropolision
  • 405
  • 4
  • 10
kappa
  • 11
  • 1
  • 5

2 Answers2

2

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);
user3437460
  • 17,253
  • 15
  • 58
  • 106
  • @kappa `but while (x == 1111 || x == 3333 || x == 4444 || x == 7777) { x = r.nextInt(9999); } `The code will work. You can test it from 1-9 and exclude 1,3,4,7. – user3437460 Nov 26 '15 at 19:03
0

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);
Jorge Campos
  • 22,647
  • 7
  • 56
  • 87