Java Reference
In-Depth Information
Classroom Q & A
Q: What are the benefits of using a switch statement?
A: Switch statements are a carry-over from C and C++, and there are
many situations where a switch statement is more elegant and
easier to write than a series of if/else statements.
Q: It seems like the StudentGrade program would have been easier
to write using a switch. Why not use a switch every time?
A: You have to be careful here. A switch statement only tests for
equality. The StudentGrade program was checking to see if a vari-
able fell within a range of values, which required less than and
greater than comparisons. You can't do those types of compar-
isons with a switch, only equality.
Q: Can you list more than one value after a single case?
A: No. If you want a case to have multiple values, you need to use the
case keyword each time followed by a single value, similar to case
B and C in the CongratulateStudent program.
Q: So you are limited by a switch statement.
A: It's not so much that you are limited, but that a switch is only use-
ful in certain situations. That being said, you never need to use a
switch statement. Every switch statement can be written using an
equivalent if/else statement. In my experience, though, program-
mers use switch statements all the time.
The while Loop
A while loop is a control structure that allows you to repeat a task a certain
number of times. The syntax for a while loop is:
while( Boolean_expression )
{
//Statements
}
When a while loop is first reached, the Boolean expression is checked. If the
Boolean expression is true, the statements in the body of the loop execute. The
flow of control then goes back up to the Boolean expression, which is checked
again. If it is still true, the statements in the loop execute again. This process
repeats until the Boolean expression is false.
Search WWH ::




Custom Search