Hello,
we had our fifth lab today. Continue with selection topic. Today's lab covers
switch statement, logical operators and conditional operator.
Switch
statements must yield a value of char, byte, short or int type and must always
be enclosed in parentheses. The keyword break is compulsory and must be used at
the end of each case. If the break statement is not present, the next class
statement will be executed.
There
are three logical operators that are used to compare values. They evaluate
expressions down to Boolean values, returning either True or False. These
operators are and (&&), or (||) and not (!).
The
conditional operator is also known as the ternary operator. It consists of
three operands and is used to evaluate Boolean expressions. For example, if (x > 0) y = 1 else y = -1 is equivalent
to y = (x > 0)? 1 : -1
There
were some exercises given by lecturer during lab. Hope you find it helpful.
*
For and (&&) statement, if wrong in either statement, result will show
false.
For or (||) statement, if correct in either
one statement, result will show true.
For not (!) statement, it means opposite to
the statement.
2. (a) if-else
statement
(b) switch statement
* Since a = 3 , any number other than 3 will be ignored. Hence, 1 + 16 = 17.
* Flowchart for switch
statement
3.
* Switch statement is
rewrite using if-else statement.
4.
*A switch statement in
displaying the days by using the keyword switch, case and break .( Sunday,
Monday, Tuesdy, Wednesday, Thursday,Friday and Saturday)
5.
* Switch statement in dislaying months by using formula that randomly generates integer between 1-12.( Same solution as question 4)
6.
*if-else statement
rewrite using conditional operator.
7.
*
Statement with using conditional operators can also be changed to if-else
statements by using keyword if else.
(a)
(b)
(c)
8.
*A
question asked to write two programs to read in three numbers from the console
and output if the numbers are sorted or not using if-else statement and using
conditional operators.
(a)if-else statement
(b) Using conditional operator
9.
*We
were asked to write a java program to count income tax for different status
with different income. First, we need to prompt user to enter the status 0 - 3
(0 for single filers, 1 for married filing jointly or qualified widow(er), 2
for married filing separately, 3 for head of household.) After that, we use
switch statement to count the income tax by using different formula. The
answers are as following.
At
the end of lab, I am able to understand switch statement, logical and
conditional operator in more comprehensive way. We must know the basic first
before doing question. Because every problems come first with basic. We able to
solve the problem and get the correct solution as long as we think logically by
following the basic(principle).
Thank you ^^
LIM XUE TING
183615
SSK3100 (Group15)
Next blog: hennyabigail.blogspot.com (Henny Abigailwillyen Sinjus)
No comments:
Post a Comment