Programs That Can Compare
Learn how to choose portions of code to execute.
Project requirements
Let’s attend to our client’s requirements for the project once again, this time focusing on the requirements highlighted in green for updating the score when the user answers a maths question correctly.
What if
We know we’ll only need ==
to check for the answer’s correctness. What if we had something in Java that could let us update the score, but only if
the userAnswer == correctAnswer
:
if (userAnswer == correctAnswer) {score = score + 1;}else {System.out.println("Unfortunately, your answer is not correct.");}
Now, this code reads neatly. This is as easy as it looks—Java lets us use if-else
to control the flow of code execution.
Either the IF or ELSE block will work, but never both, based on the condition being true or false. Can you tell?
Which line number will not get executed when the value of userAnswer
is equal to correctAnswer
in the code above?
Line 1
Line 2
Line 4
Line 5
Bringing if
inside our project
Let’s ...