Practice Challenges for Fun
This lesson has some challenging problems for you to solve.
We'll cover the following...
Quiz
Attempt the following quiz questions:
Consider the following if
statement:
if (x > 2)
{
if (y > 2)
{
z = x + y;
System.out.println("z is " + z);
}
}
else
System.out.println("x is " + x);
What is displayed when the values of x
and y
are 3 and 2, respectively?
Nothing is displayed
x is 2
z is 7
Error
Consider the following if
statement that classifies people according to their age. The programmer who wrote this code was careless when indenting. The syntax, however, is correct. Assume that age
is an int
variable containing a positive value.
int age;
.
.
.
// age now contains a positive integer.
if (age < 12)
System.out.println("You belong to Group 1");
else if (age > 12)
if (age <= 19)
System.out.println("You belong to Group 2");
else if( (age > 20) && (age < 55) )
System.out.println("You belong to Group 3");
else
System.out.println("You belong to Group 4");
else
System.out.println("You belong to Group 5");
How old are the people in Group 1?
What multiway if
statement will decide the percentage increase of an employee’s salary based on the following merit rating scale?
Rating % Increase
95 and above 5.0
80 to 94 2.5
Below 80 1.25
Assume that the int
variable sumCode
has been assigned a value. Rewrite the following multiway if
statement as a switch
statement:
if (sumCode == 1)
sum = sum + 2.5;
else if (sumCode == 2)
sum = sum + 5.0;
else if (sumCode == 3)
sum = sum + 7.5;
else if (sumCode == 4)
sum = sum + 10.0;
else
sum = 0;
Challenge 1: Read an answer to a question and react to it
Write some code that displays a question whose answer is yes or no. Read the answer as a string.
- If the answer is
yes, display
You answered YES!
. - If the answer is no, display
You answered NO!
. - If the answer is longer than three characters, display
Your answer is too long!
. - If the answer has three or fewer characters, but