Read this chapter, which discusses the switch and '?' operators to write conditional statements. As you read this tutorial, you will learn that sometimes it is better to use a 'switch' statement when there are multiple choices to choose from. Under such conditions, an if/else structure can become very long, obscure, and difficult to comprehend. Once you have read the tutorial, you will understand the similarity of the logic used for the 'if/else' statement, '?', and 'switch' statements and how they can be used alternately.
4. More Complicated Expressions
Answer:
int a = 7, b = 21;
System.out.println( "The min is: " + (a < b ?
a :
b ) );
More Complicated Expressions
Here is a slightly more interesting example:
A program computes the average grade of each student in a class. Students whose average grade is below 60 are given a bonus of 5 points. All other students are given a bonus of just 3 points.
Here is the program fragment that does this:
... average grade is computed here ...
average += (average < 60 ) ? 5 : 3;
The subexpressions that make up a conditional expression can be as complicated as you want. Now say that grades below 60 are to be increased by 10 percent and that other grades are to be increased by 5 percent.
Here is the program fragment that does this:
... average grade is computed here ...
average +=
(average < 60 ) ? average*0.10 : average*0.05;
This is probably about as complicated as you want to get with the conditional operator. If you need to do something more complicated than this, do it with if-else
statements.
Question 4:
Write an assignment statement that adds one to the integer number
if it is odd, but adds nothing if it is even.