I am trying to generate random number, but also I want to count how many times does it take to generate specific number and show random number which was generated.
So far, my code works just how I wanted, but I feel it could be written easier and more precisely, since I need to set random number range twice.
Random r = new Random(); int x = r.nextInt(50)+1; int o = 0; while(x!=15) { o++; System.out.println("Try number: " + o + " and random number is: " + x); x = r.nextInt(50)+1; } System.out.println("The answer is 15!"); }
Advertisement
Answer
You could eliminate the redundant assignment by changing from a while
loop to a do-while
loop. Like,
int x; int o = 0; do { x = r.nextInt(50) + 1; System.out.println("Try number: " + o + " and random number is: " + x); o++; } while (x != 15); System.out.println("The answer is 15!");