I have been trying to write code, which makes the machine guess a random number from 1 to 1000. Because I know how to write it in pascal and python, I tried to write it in java, but I'm stuck now.
Here is the code:
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void main(String[] args) {
int random = ThreadLocalRandom.current().nextInt(0, 1000);
int count = 0;
do {
int answer = ThreadLocalRandom.current().nextInt(0, 1000);
count++;
} while (random != answer);
System.out.println("Answer: " + answer + " " + "Count: " + count);
}
}
The problem is, that in this line
} while (random != answer);
answer
is not defined.
I am trying to do the loop, until random
equals answer
.
The question is, how do I define the answer
variable as a random changing number, while the variable random
stays the same?
Thanks in advance!
You have to define int answer
outside of the do{}while(...)
:
public static void main(String[] args) {
int random = ThreadLocalRandom.current().nextInt(0, 1000);
int count = 0;
int answer;
do {
answer = ThreadLocalRandom.current().nextInt(0, 1000);
count++;
} while (random != answer);
System.out.println("Answer: " + answer + " " + "Count: " + count);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.