Tip:
Highlight text to annotate it
X
We now consider a conditional statement.
Conditionals allow us to have code happen only
if a certain condition is true.
In the class SimpleIf, we create a Scanner object named inputScanner,
and use its nextDouble method to read a GPA from the keyboard.
If the GPA is at least three point oh, then we will print a message
congratulating the student on making the Dean’s list.
If not, it does nothing.
Note in either case the program continues after the
closing curly brace for the if, so the message “the end”
will always be printed.
We will now compile and run the program.
It is useful to test the boundary cases,
so in addition to testing a GPA below 3.0 and a GPA above 3.0.
We'll also test 3.0.
The keyword “else” allows us to set up an either-or scenario.
In the class SimpleIfElse, we again read a GPA from the keyboard.
This time, we either print “academic probation”
if the GPA is less than 2 point 0, or “academically proficient” otherwise.
We now compile and run the program.
Again, we'll test below, above, and exactly 2.0.
We can set up multiple paths through the code using “else if”.
In the class IfElseIf, we convert an exam score
to a letter grade using the 10 point scale.
We look at each possibility in turn, until we find one that is true,
and then print the appropriate message.
In Java, ampersand ampersand is used to mean “and”.
Similary “pipe” “pipe” may be used for or.
Since the “else” means that the first condition must be false,
it is redundant to have a test to make sure the score is less than 90.
We can remove these extraneous tests to make the
program more efficient and easy to read.
In an If/Else If statement,
it keeps looking at the conditions until it finds one that is true.
It will then skip over all of the others past the closing curly brace.
This means the order is important.
If we put the “score >=80” first, and type in 95,
then it will print “B”, and not get to the test for score >= 90.