Simple Selection Statements

Things To Do First

Things To Do Later

If Statements

Read!
First, read Chapter 3.3

In programming, we use If Statements to allow our programs to make decisions. For example, a program might want to ask the user if they're sure they want to exit a program, and if the user says yes, the program terminates. In another example, a program might ask the user to enter a log-in name to use an order entry system. If the name is valid, the order entry screen is displayed. If the name is not valid, an error message appears.

If statements can be single-sided, double-sided, or can be multi-sided. We'll look at each of these and try some examples.

Single-Sided Ifs

A single sided If in Java has the general form:

if (relationalExpression) {
	// code to execute if relationalExpression
	// evaluates to true
}

The if-block (the code between the braces) only executes if the relational expression evaluates to true. If there is only one statement in the if-block, you can omit the braces. For example, this is perfectly valid:

if (x > 3)
	System.out.println("x is larger than 3");

However, this code below will not give the results you would expect:

if (x > 3)
	System.out.println("x is larger");
	System.out.println(" than 3);

In this example, the second print statement is not part of the if-block and will be executed regardless of whether or not x > 3 is true or false. To try this out, you can enter this code segment into a new program and declare/initialize the variable x to 5, then run the program. Then change x's value to 2 and run the program.

For beginning programmers, or programmers new to a Java style of syntax, I would get into the habit of leaving the braces on all the time until you become comfortable with leaving them off. As you'll see later on, leaving off the braces at the wrong time can cause some serious logic errors.

Exercise

[Solutions]

1. Write a program that asks the user for a number less than 100. If the user's input is 100 or more, display a message on the console.

2. Modify the program: Instead of checking to see if the number is 100 or more, check to see if the number is less than 100. If it is, calculate the square root of the number, the square of the number, and the cube of the number. Then display these on the console.

Double-Sided Ifs

Read!
First, read Chapter 3.4

A double-sided if has two actions: one to perform if the condition is true, and one to perform if the condition is false. The general form of the double-sided If statement is:

if (relationalExpression) {
	// code to execute if relationalExpression
	// evaluates to true
} else {
	// code to execute if relationalExpression
	// evaluates to false
}

Note that we still only have one condition, but now we have two blocks of code. The if-block executes when the condition is true, and the else-block executes when the condition is false. Only one of the two blocks will execute!

As with the single-sided If, if you have only one code statement in either the if-block or the else-block, you can leave off the braces. For example, all of these are acceptable:

if (x > 3) 
	System.out.println("x is bigger than 3");
else
	System.out.println("x is 3 or less");
...
if (x > 3) {
	System.out.println("x is bigger");
	System.out.println(" than 3");
} else
	System.out.println("x is 3 or less");
...
if (x > 3)
	System.out.println("x is bigger than 3");
else {
	System.out.println("x is 3");
	System.out.println(" or less");
}

Exercises

[Solutions]

Write programs for each of the following:

  1. Ask the user for a whole number. Display a message on the screen that indicates whether the number is even or odd.
  2. The method Math.random() generates a random double number greater than 0.0 and less than 1.0. Write a program that simulates flipping a coin. Call the Math.random() method and if the number generated is less than .5, display "HEADS". Otherwise, display "TAILS".
  3. Write a program that generates a random integer from 1 to 5. Then ask the user to guess that number. If they guess correctly, display the message, "You guessed correctly!". If they guess incorrectly, display the message, "Sorry, you guessed incorrectly."
  4. Write a program that simulates the tossing of two dice (generate two random integers from 1 to 6). If doubles are rolled, display a "You Win!!" message. Otherwise, tell the user what dice values they rolled.
  5. In a bank where you work, money is given an interest rate of 7.5% if it is left in an account for more than 5 years; otherwise, the interest rate is 4.5%. Write a program that asks the user for their current account balance, and number of years their money has been sitting in the account. Then assign the proper interest rate to a variable interestRate. Finally, calculate and display the total interest for the current year
  6. A program calculates a person's weekly pay based on the following: If the hours worked are less than or equal to 40, the person receives 10 dollars per hour; otherwise, the person receives 10 dollars for the first 40 hours and then 15 dollars for the hours they work over 40. Your program should ask for the number of hours from the user, and then calculate the weekly pay. Display your result.
  7. Write a program that checks for a valid department number entered by the user. A department number is valid if it is between 1 and 45, inclusive. Display messages stating whether or not the department number is valid.
  8. Modify the previous question: A valid department number is between 1 and 45 inclusive, or greater than 200.
  9. Modify the previous question: valid department numbers include department 50, those between 1 and 45 inclusive, and those that are greater than 200.