• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to stop boolean value going back to original value in While Loop  RSS feed

 
Damien O Sullivan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Inside a While Loop (While Loop begins if a condition is True) I have an If Statement, the else part of the statement assigns False to the condition I mentioned earlier.

But I've tried de-bugging and even when the code goes through the else part of the statement, firstly it returns False but then it returns to the beginning of the loop as True again.

I'd like to know is there a way to get around this problem that I have.

Thanks in advance for any help!
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello

How are you coding your while loop?


 
Alice Hampton
Ranch Hand
Posts: 217
Chrome Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you have any code you could show?
 
Knute Snortum
Sheriff
Posts: 4274
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you post your code (with code tags) we can take a look at it and maybe help.
 
Damien O Sullivan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


If the Student gets the question wrong they must be asked the question again but when I run the code, it goes through the loop again and generates different numbers.
 
Knute Snortum
Sheriff
Posts: 4274
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The else part of the if statement doesn't need an if unless you are starting another if statement. Try removing the if.
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your while loop is infinite because the "AnswerIsCorrect" will always be true.

These 2 lines are equivalent



The correct approach is something like:

 
Damien O Sullivan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've removed the 'else if' and replaced it with just an 'else', but it still hasn't solved the problem.

When I run the code now and get the answer wrong the first time, it repeats the same question, then when I answer it correctly the program runs as normal.

However, when I get the same question wrong twice, it generates two new numbers.
 
Knute Snortum
Sheriff
Posts: 4274
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think we need to see more of your code. But first, put in some System.out.println() statements to display what values key variables have. See if this matches you expectations.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Damien O Sullivan wrote:I've removed the 'else if' and replaced it with just an 'else', but it still hasn't solved the problem.

Because you haven't read Knute's post (2 back now).

The basic problem is NOT in the 'else', but in your while condition, which is an assignment - and I don't think you meant it to be.

'=' ASSIGNS a value, '==' checks if two values are equal. The problem is that, in Java, an assignment returns the value that was assigned.

See if you can't work out the problem now.

Winston
 
Damien O Sullivan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've changed the '=' to '==' now but after the answer is wrong two times in a row, the code goes outside of the loop. I've tried changing it a bit but it still doesn't work





 
Knute Snortum
Sheriff
Posts: 4274
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the problem is here:



Look at the API for scanner. next() just gets the next token. You probably want nextInt(), that is, you're looking for an integer in the stream.
 
Charles D. Ward
Ranch Hand
Posts: 99
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, as mentioned earlier, you should NEVER use == with booleans.

if (booleanVariable == true) { // BAD. Prone to errors like the one you did with = instead of ==
if (booleanVariable == false) { // BAD. Prone to errors like the one you did with = instead of ==

if (booleanVariable) { // Good. checking if booleanVariable is true
if (!booleanVariable) { // Good. checking if booleanVariable is false




 
Damien O Sullivan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.Random;
import java.util.Scanner;

public class SecondYearProject
{

public static void main(String args[])
{

Scanner input = new Scanner(System.in);

int FirstNumber;
int SecondNumber;
int CorrectAnswer;
int StudentGuess;
boolean AnswerIsCorrect = true;
boolean AnswerIsWrong = false;
int StudentIntAnswer = 0;

Random rand = new Random();
rand.nextInt(10);





while (AnswerIsCorrect = true)
{

FirstNumber = (rand.nextInt(10));

SecondNumber = (rand.nextInt(10));

System.out.println("What is " + FirstNumber + " times " + SecondNumber + "?");

CorrectAnswer = FirstNumber * SecondNumber;

Scanner StudentAnswer = new Scanner(System.in);

StudentGuess = StudentAnswer.nextInt();

// StudentIntAnswer = Integer.parseInt(StudentGuess);
StudentIntAnswer = StudentGuess;

if (StudentIntAnswer == CorrectAnswer)
{
System.out.println("very good");
}

else
{


System.out.println("WRONG");
System.out.println("What is " + FirstNumber + " times " + SecondNumber + "?");
AnswerIsCorrect = false;

StudentGuess = StudentAnswer.nextInt();
StudentIntAnswer = StudentGuess;
if (StudentIntAnswer == CorrectAnswer)
{
AnswerIsCorrect = true;
}


}

}//end of while









}//end of main method

}//end of class

With this code when I get the answer wrong twice in a row, it changes the number values
 
Knute Snortum
Sheriff
Posts: 4274
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's wrong with this code?

 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Charles D. Ward wrote: . . . you should NEVER use == with booleans. . . .
Exception
if (b1 == b2) …

But that should not be a frequent occurrence; it is as error‑prone as writing
if (b == true) …


Damien O Sullivan:
Thank you for using code tags, but please look at this link; you didn't place them correctly and I have corrected them. I also got rid of the excess blank lines, which don't help legibility. Also broke two lines as being too long, and you can see how to do it for next time.
You have a boolean for right answer and one for wrong answer. Not at all good. You only want one, unless you want the situation where both have the same value
You also have two Scanners. You only want one.

You have not worked out what you want to happen when something goes wrong. What would have happened if Douglas Adams had ever tried such a program?
What is 6 times 9?
42
Well, what is supposed to happen then? Your else block looks as if you had guessed about what to write.
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See Charles D Ward's reply and heed his advice. Your code will be better and you won't get the kind of bugs that Knute is highlighting.
 
Damien O Sullivan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute Snortum wrote:What's wrong with this code?


Should it be (AnswerIsCorrect)
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:
Charles D. Ward wrote: . . . you should NEVER use == with booleans. . . .
Exception
if (b1 == b2) …

You can use the XOR operator which returns true if both booleans are the same  different

*Edit: above checks if b1 is different from b2. Thanks, Campbell, for pointing that out

but you seldom see the ^ operator used and it may not be as obvious as == to some people.
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Damien O Sullivan wrote:Should it be (AnswerIsCorrect)

Yes. If you read it out loud, it (almost) sounds like normal conversation, doesn't it? That's what your code should be like. Code should be human-readable and it should tell a story of what's happening in the program.

BTW, your use of capitalization is not the standard convention in Java programs. Variable names start with a lowercase letter. Class names are capitalized.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote: . . .
You can use the XOR operator which returns true if both booleans are the same
. . .
You sure about that? XOR returns whether the two are different.
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:
Junilu Lacar wrote: . . .
You can use the XOR operator which returns true if both booleans are the same
. . .
You sure about that? XOR returns whether the two are different.

Oh, my bad. You can tell I don't use it much either
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmm I guess you didn't noticed my second post mentioning your while loop is infinite.


Anyway when the user has incorrect answer the first time, what is the expected result? Prompt again or exit the loop? Implementing the former can be a bit tricky. The latter, you can use the "break" keyword, but that's not good practice IMO.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can only remember wanting ^ on booleans once.

 
Damien O Sullivan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



At this point, when I enter the incorrect answer in two times in a row, the operation completes.

I need the program to keep repeating the same question until the user enters the correct answer, then generate a new question.
 
Knute Snortum
Sheriff
Posts: 4274
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try writing the logic down on a piece of paper, in English. Then translate it into code.

Hint: will one loop do everything you need?
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, think about it:

Your program says: while answerIsCorrect

So, when the user enters the wrong answer, is the answer correct? Should the while continue?
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And step through your logic. When the user enters a wrong answer, then enters the right answer, what happens to the variable AnswerIsCorrect? Is it true or false? It should be true, but is it?
 
Damien O Sullivan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've had to scrap my original code 'cause it was becoming too complicated so this is what I have at the moment:



At the moment this code tells me if the answer is right or else it prints out the same question again, but the operation completes then.

Can you give me a hint as to what I should do next please.
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Damien O Sullivan wrote:Can you give me a hint as to what I should do next please.

StopCoding and walk through your logic. Get a pencil and a piece of paper and step through each instruction you've given in the program. Note down the value of each variable as you go and see if it is actually what you think it should be. If you do this, you should be able to see where you're going wrong. Sometimes it helps to tell someone else what your program is doing. If you have nobody there, pick up any inanimate object (traditionally, it's a rubber duck) and try to explain to it what you're trying to do and what's actually happening at each step of the program.
 
Damien O Sullivan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've ran through the original code now and when I answer incorrectly the second time, AnswerIsCorrect = False and it exits the loop.
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Damien O Sullivan wrote:I've had to scrap my original code 'cause it was becoming too complicated so this is what I have at the moment:

So you've learned an important lesson: DON'T make your code too complicated. Keep It Short and Simple (KISS)

I don't know if you have learned about methods yet but one way to reduce complexity is to break the problem down to small chunks. That is, instead of having one humungous method with 50 or more lines of code and multiple flow control structures (while-loop, if-statements, etc), it's easier to keep a handle on what's happening when you have multiple methods that each do one small task. Like check if the answer matches the solution. Or get input from the user. Or display a prompt or message. Then you'll have one main method that calls upon all these "helper" methods. The main method is an outline of the logic and tells the main story. The helper methods are like little sidebars that explain how each task is done. Again, you may not be at a point where this makes sense yet but keep this in the back of your mind for later -- it's what will help you keep your sanity as well as those of others.
 
Damien O Sullivan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you tell me if I'm using the right type of loop and if I should place the If Statement inside or outside of it?

I've tried writing it down and still don't know how to get around it.
 
Charles D. Ward
Ranch Hand
Posts: 99
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a logic problem, not something related to Java or ifs or loops. Just logic.

Write down the problem in english and then deconstruct the problem into small steps. Only when you have the solution you should start "translating" it into Java code.

Forget ALL about while or for loops, ifs and Java for the moment. Write down the logic first.
 
Damien O Sullivan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Shouldn't the final Else run the If part again? Instead it just ends the program
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Damien O Sullivan wrote:Shouldn't the final Else run the If part again? Instead it just ends the program

if-else doesn't work like that. It's a simple, straight through execution. That is, given something like this:

if the condition evaluates to true, execute the body of the if-statement
otherwise execute the body of the else clause

After this is done, execution continues to whatever follows, it does not go back to the if part. Only a loop will do what you think should be happening.

 
Damien O Sullivan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:
Damien O Sullivan wrote:Shouldn't the final Else run the If part again? Instead it just ends the program

if-else doesn't work like that. It's a simple, straight through execution. That is, given something like this:

if the condition evaluates to true, execute the body of the if-statement
otherwise execute the body of the else clause

After this is done, execution continues to whatever follows, it does not go back to the if part. Only a loop will do what you think should be happening.



What should I use so to get the program to repeat the same question again?
 
Damien O Sullivan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


When the answer is answered incorrectly twice, the program closes, I can't get it to go back into the loop and ask the same question again.

How do I get the code to jump back into the "if (CorrectAnswer != StudentIntAnswer)"?
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Damien O Sullivan wrote:What should I use so to get the program to repeat the same question again?

The quickest thing to do is right now (although it doesn't do anything to make your code cleaner) is to add something that says:

if (answer is not the right one)
// ???

after the user enters the wrong answer again. The ??? needs to be some statement that can affect whether or not the while-loop will continue to execute. That's really all you're missing right now. Again, it's not pretty but it will work.

Edit: I take that back. I see you got it to work somewhat. So all you want to do now is to make it go back and ask the same question again. Then what's the point of putting logic to make it ask a second time? Do you want to keep asking the same question until they get the correct answer or do you only want to give them two chances to get it right?
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One thing that's probably adding to your confusion is your unconventional indentation style. With better indentation, it's easier to see how the logic flows. I've fixed up the indentation for you here:
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!