Random 1-10 guessing game with 3 tries
Hi guys,
I've got some what of an easy problem I would guess, I just think that I have my function in the wrong place. This is an assignment in class that I have had much issues with trying to get it to break out of a while loop using boolean variables (because break is bad coding practice). Anyways, I've tried using regular int boolean such as Code:
int test = 0;
...
while (test ==0) {...
}
test = 1;
and I have not had much luck. If you could help it would be great! Thanks, -Seth
Re: Random 1-10 guessing game with 3 tries
To break out the while loop your 'test ==0' needs to become true at some point in the while loop. The while loop will not do anything as it is true to begin with. Because the variable test is 0 to start off with.
Re: Random 1-10 guessing game with 3 tries
I posted the code separately to be easier to read: I did not include the header so you can run this on an open program.
Code:
boolean quit = false;
int i = 0;
while (quit == false) {
Random seed = new Random();
int answer = seed.nextInt(10);
System.out.println(answer);//remove later
Scanner input = new Scanner(System.in);
int guess = input.nextInt();
if (guess > answer) {
System.out.println("Your guess is too high \n");
} else if (guess < answer) {
System.out.println("Your answer is too low \n");
}
//*************************************************
while (guess != answer) {
i++;
if (i==3){
quit = true;
System.out.println("Test");
}
System.out.println("this is i:" + i);
int retry = input.nextInt();
if (retry > answer) {
System.out.println("Your guess is too high \n");
} else if (retry < answer) {
System.out.println("Your answer is too low \n");
}
if (retry == answer) {
guess = answer;
}
}
System.out.println("You win!");
}
System.out.println("Sorry you lose :(");
}
}
Re: Random 1-10 guessing game with 3 tries
Well for my instance, would it be possible to convert it to true by using if statements and counters?
Code:
boolean test = false;
int i = 0;
while (test ==false) {
i++;
... if (i =3) {
test = true
}
Re: Random 1-10 guessing game with 3 tries
This will not stop your main loop:
Code:
if (i == 3) {
quit = true;
System.out.println("Test");
}
as it is stuck in the while (guess != answer) { loop.
You need to break out of this loop:
while (guess != answer) {
before breaking out of this: while (quit == false) {.
Re: Random 1-10 guessing game with 3 tries
Quote:
Originally Posted by
sethe23
Well for my instance, would it be possible to convert it to true by using if statements and counters?
Code:
boolean test = false;
int i = 0;
while (test ==false) {
i++;
... if (i =3) {
test = true
}
Yea, you can do something like this.
Re: Random 1-10 guessing game with 3 tries
I figured it was something simple like placement. I am not exactly sure how I could break out of the whole while (guess!=answer) entirely. I thought by making it equal true in the program would break the statement.