Working with Conditional Statements - Java eLearning Kit For Dummies (2014)

Java eLearning Kit For Dummies (2014)

Chapter 6. Working with Conditional Statements

· Using a simple if statement allows your application to decide whether to take a particular action.

· Relying on the if...else statement lets your application choose between two actions.

· Placing one if statement within another helps your application perform complex decision making.

· Employing a switch statement lets the application choose one action from multiple actions.

· Defining a default option makes it possible for the application to perform a specific task when no other tasks are selected.

· Converting Boolean values to human-readable form makes the application easier to use.

lingo_fmt.tif

1. Is it possible to make simple decisions based on any criteria?

Java makes it possible to perform simple decision-making tasks with the if statement, as described on page 167

2. How do I create code that performs just one of two tasks in a given situation?

The use of an if...else statement makes it possible to perform just one of two tasks, as shown on page 169

3. What if I need to make a basic decision and then make additional decisions based on that original decision?

Nesting if statements make it possible to achieve any level of complexity in decision making, as described on page 171

4. How can my application choose one option from many?

When your application needs to choose just one action from an entire menu of options, use the switch statement, as described on page 174

5. I’m not sure that a user will select any of the options, so how can my application control that situation?

Relying on default actions makes it possible to do something, even if the user or other decision-making party can’t determine what to do, as described on page 177

6. Can I display something other than true or false when working with Boolean values?

Fortunately, it’s possible to display Boolean values in other forms such as Yes and No, as shown on page 180

“If you read this book from end to end, then you’ll know quite a bit about Java when you’re finished.” This is a human form of a conditional statement. A conditional statement in an application begins with a condition and ends with a task. You use conditional statements every day. Another example of a conditional statement is, “Choose the item that most closely matches your age from this list for your prize.” Programs can use that sort of conditional statement too! The main purpose of this chapter is to show you how to write conditional statements in a way that the computer understands; but from a logical perspective, you already know everything required to use conditional statements.

Using a Simple If Statement

The if statement is the easiest of the conditional statements to understand and you’ll find that you use it often. An if statement consists of a condition that looks like this:

if (expression)


LINGO

Computers rely heavily on math used to express an idea to make certain decisions. Consequently, the condition part of a conditional statement is also called an expression. An expression always equates to a value of true or false, so it’s a Boolean value. However, when you think about it, you use Boolean expressions in your daily conversation. For example, “If the item costs less than $5.00, then I’ll buy it.” The condition — item costs less than $5.00 — is a Boolean expression.


where expression is the condition that you want to check. The task associated with the if statement appears within curly braces like this:

{
Tasks you want to perform ...
}

Every if statement follows the same pattern of condition followed by task. With this pattern in mind, in the following example you create an application that relies on an if statement to make a decision about a number that you type.

Files needed: SimpleIf.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the Editor screen.

// Import the required API classes.
import java.util.Scanner;

public class SimpleIf
{
public static void main(String[] args)
{
// Create the scanner.
Scanner GetInput = new Scanner(System.in);

// Obtain a byte value.
System.out.print("Type any number: ");
int Input = GetInput.nextInt();

// Determine whether Input is less than 5.
if (Input < 5)
{
System.out.println("The input is < 5.");
}

// Determine whether Input is greater than or
// equal to 5.
if (Input >= 5)
{
System.out.println("The input is >= 5.");
}
}
}

This application obtains an integer value as input from the console. It then checks this value against the number 5 by using two if statements. The first statement determines whether Input is less than 5. If so, it outputs a message saying so. Likewise, the second statement determines whether Input is greater than or equal to 5 and outputs the appropriate message when true. The application will select one if statement or the other, but never both.

3. Save the code to disk using the filename SimpleIf.java.

4. In your command prompt, type javac SimpleIf.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java SimpleIf and press Enter.

The application asks you to type a number. Make sure you type a whole number and not a floating point number or a character.

6. Type 4 and press Enter.

The application outputs a message stating, The input is < 5.

7. Repeat Steps 5 and 6, but substitute a value of 5 this time.

The application outputs a message stating, The input is >= 5.

8. Repeat Steps 5 and 6, but substitute a value of 6 this time.

The application outputs a message stating, The input is >= 5., as shown in Figure 6-1.

9781118098783-fg0601.tif

Figure 6-1:

Performing One of Two Tasks with If…Else

The basic if statement could be used for every task. However, writing code using just the basic if statement can become boring and even introduce errors (bugs) into your application. Look again at the example in the “Using a Simple If Statement” section of the chapter, and you see that it has two if statements in it. The if...else statement makes it possible to perform precisely the same task using just one structure. The if...else statement says that if the condition is true, the application should perform one set of tasks, but if the condition is false, it should perform a completely different set of tasks.


LINGO

A bug is an error in the code that you write. Errors make your application behave in ways that you didn’t anticipate. Anyone using your application will get results different from the results you wanted to provide them with. Bugs cause all sorts of problems. For example, a bug in the wrong place could cause your application to stop working or give a virus writer an opportunity to invade your application. Simplifying your code and using the appropriate statements is one way to decrease bugs.


The example in the “Using a Simple If Statement” section of the chapter is awkward and you can easily improve it. The following example shows how to use an if...else statement to make the code easier to read and understand. The change also reduces the risk of seeing a bug in the application.

Files needed: UsingIfElse.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.util.Scanner;

public class UsingIfElse
{
public static void main(String[] args)
{
// Create the scanner.
Scanner GetInput = new Scanner(System.in);

// Obtain a byte value.
System.out.print("Type any number: ");
int Input = GetInput.nextInt();

// Determine whether Input is less than 5.
if (Input < 5)
{
// Input is less than 5.
System.out.println("The input is < 5.");
}
else
{
// Input is greater than or equal to 5.
System.out.println("The input is >= 5.");
}
}
}

This application obtains an integer value as input from the console. It then checks this value against the number 5 by using an if...else statement. When Input is less than 5, the application performs the first task; but when it’s greater than or equal to 5, the application performs the second task.

tip.eps Interestingly enough, this version of the application is one line shorter than the previous version. When you use the various shortcuts shown in this chapter, you not only make your application less prone to errors, but you also save time typing code.

3. Save the code to disk using the filename UsingIfElse.java.

4. In your command prompt, type javac UsingIfElse.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java UsingIfElse and press Enter.

The application asks you to type a number. Make sure you type a whole number and not a floating point number or a character.

6. Type 4 and press Enter.

The application outputs a message stating, The input is < 5.

7. Repeat Steps 5 and 6, but substitute a value of 5 this time.

The application outputs a message stating, The input is >= 5.

8. Repeat Steps 5 and 6, but substitute a value of 6 this time.

The application outputs a message stating, The input is >= 5., as shown in Figure 6-2.

9781118098783-fg0602.tif

Figure 6-2:

9. Compare Figure 6-1 with Figure 6-2.

Notice that both versions of the application behave precisely the same.

Nesting If Statements

Sometimes a decision requires multiple levels. For example, if the ceiling is painted orange, then you may also need to decide whether the walls are painted yellow or red. Another form of multiple level decision-making is a menu. A user may have to decide between items A, B, or C, but isn’t allowed to pick two at the same time (items A and B). Fortunately, you can create as many levels of if statements as required to handle this problem. Combining multiple levels of if statements to make complex decisions is called nesting.


LINGO

Nesting makes it possible to create multiple decision-making levels within an application. You can combine all sorts of statements into a cohesive unit in order to make a decision. Nesting lets you focus on a particular part of the decision-making process and perform the process one step at a time, rather than creating a horribly complex expression.


Menus are one of the decision-making processes you’ll encounter quite often in applications. Most real world decisions aren’t just between this or that, but rather they involve shades of gray, as in “You must choose one item from a list of possible choices.” The following example demonstrates how to use nesting to create a menu system.

Files needed: UseAMenu01.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.util.Scanner;
import java.lang.Character;

public class UseAMenu01
{
public static void main(String[] args)
{
// Create the scanner.
Scanner GetChoice = new Scanner(System.in);

// Obtain input from the user.
System.out.println("Options\n");
System.out.println("A. Yellow");
System.out.println("B. Orange");
System.out.println("C. Green\n");
System.out.print("Choose your favorite color: ");
char Choice = GetChoice.findInLine(".").charAt(0);

// Convert the input to uppercase.
Choice = Character.toUpperCase(Choice);

// Determine if the input is an A.
if (Choice == 'A')
System.out.println("Your favorite color is 
Yellow!");

// Determine if the input is a B.
else if (Choice == 'B')
System.out.println("Your favorite color is
Orange!");

// The input could be a C.
else if (Choice == 'C')
System.out.println("Your favorite color is
Green!");
}
}

The application begins by creating a Scanner (GetChoice) and using it to obtain char input (Choice) from the user. Because you can’t be sure whether the user has entered an uppercase or lowercase letter, you need to convert the letter to uppercase. The code relies on the static method,Character.toUpperCase() to perform this task.


EXTRA INFO

Converting a character to uppercase is one of the special situations where you change data state between a primitive type and an object. In this case, Choice is a char, which is a primitive type. The application momentarily boxes Choice as a Character, calls toUpperCase() to convert the case, and then unboxes the result back intoChoice.


After the input is converted, the application uses it to make a choice. The user can input any of the three choices, but there’s actually a hidden fourth choice. The user can also choose not to provide any of the specific input. For example, the user could type 3 instead of c or C. Consequently, the code must check the input up to three times in order to determine the user’s choice.

3. Save the code to disk using the filename UseAMenu01.java.

4. In your command prompt, type javac UseAMenu01.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java UseAMenu01 and press Enter.

The application asks you to choose a letter associated with a color.

6. Type A and press Enter.

The application outputs the expected message.

7. Repeat Steps 5 and 6, but substitute a value of b this time.

The application outputs the expected message again. Notice, however, that it doesn’t matter whether the input is uppercase or lowercase, you still get the expected result.

8. Repeat Steps 5 and 6, but substitute a value of 3 this time.

The application doesn’t output anything, as shown in Figure 6-3. Notice also in Figure 6-3 that the application provides a nice appearance for the menu system. For example, there is an extra line between Options and the list of options. That’s the purpose of the \n escape code shown in the listing. Ending a string with a \n escape code will add an extra line and provide a pleasing appearance to the user.

9781118098783-fg0603.tif

Figure 6-3:

tip.eps Providing the right prompt can make a big difference in the usability of your application. For example, if you were to provide a list of valid options for the user of this application, such as Choose A, B, or C, you could make it less likely that the user will make an invalid choice. Even so, users do make invalid choices despite the best prompts, so your application code must also provide robust error handling.

Selecting from Multiple Conditions Using Switch

Just as there’s a shortcut for using two if statements in the if...else statement, there’s a shortcut for using multiple if...else statements to create a menu in the switch statement. The switch statement consists of a condition that looks like this:

switch (variable)

where variable contains a value you want to check against a number of constants. The constants appear as part of a case clause like this:

case value:

where value is a specific constant value you want to check. Finally, the task appears after the case clause and ends with a break clause like this:

task;
break;

You must include the break clause to tell the compiler when the task is finished.

The switch statement makes it possible to create a menu system in a way that’s easy to read and a lot shorter to type. In the following example, you create an application that relies on the switch statement to allow the user to select from one of several options.

Files needed: UseAMenu02.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.util.Scanner;
import java.lang.Character;

public class UseAMenu02
{
public static void main(String[] args)
{
// Create the scanner.
Scanner GetChoice = new Scanner(System.in);

// Obtain input from the user.
System.out.println("Options\n");
System.out.println("A. Yellow");
System.out.println("B. Orange");
System.out.println("C. Green\n");
System.out.print("Choose your favorite color: ");
char Choice = GetChoice.findInLine(".").charAt(0);

// Convert the input to uppercase.
Choice = Character.toUpperCase(Choice);

// Choose the right color based on a switch

// statement.
switch (Choice)
{
case 'A':
System.out.println("Your favorite color is
Yellow!");
break;
case 'B':
System.out.println("Your favorite color is
Orange!");
break;
case 'C':
System.out.println("Your favorite color is
Green!");
break;
}
}
}

This application begins precisely like the UseAMenu01 application does by displaying a menu of selections and asking the user to select one. In addition, it ensures that the input is converted to uppercase as needed. The switch statement compares Choice to three case clauses; A, B, and C. When Choice equals one of these constants, the application performs the task associated with that case statement and stops when it sees the break clause.

3. Save the code to disk using the filename UseAMenu02.java.

4. In your command prompt, type javac UseAMenu02.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java UseAMenu02 and press Enter.

The application will ask you to choose a color.

6. Type A and press Enter.

The application outputs the expected message.

7. Repeat Steps 5 and 6, but substitute a value of b this time.

The application outputs the expected message again.

8. Repeat Steps 5 and 6, but substitute a value of 3 this time.

The application doesn’t output anything, as shown in Figure 6-4.

9781118098783-fg0604.tif

Figure 6-4:

9. Compare Figure 6-3 with Figure 6-4.

Notice that both versions of the application behave precisely the same.

Executing a Default Task

The UseAMenu01 and UseAMenu02 applications suffer from a particular problem. When the user types an unexpected letter, number, or symbol, the application simply ends and doesn’t display anything. This response is better than allowing the application to crash, but it hardly tells the user what went wrong. In this case, you need a default action to help the user understand what’s wrong. Default tasks make it possible for the application to do something, even when the user doesn’t provide the expected input. In the following exercise, you create a new version of UseAMenu02 and add a default task to it.

Files needed: UseAMenu03.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.util.Scanner;
import java.lang.Character;

public class UseAMenu03
{
public static void main(String[] args)
{
// Create the scanner.
Scanner GetChoice = new Scanner(System.in);

// Obtain input from the user.
System.out.println("Options\n");
System.out.println("A. Yellow");
System.out.println("B. Orange");
System.out.println("C. Green\n");
System.out.print("Choose your favorite color: ");
char Choice = GetChoice.findInLine(".").charAt(0);

// Convert the input to uppercase.
Choice = Character.toUpperCase(Choice);

// Choose the right color based on a switch

// statement.
switch (Choice)
{
case 'A':
System.out.println("Your favorite color is
Yellow!");
break;
case 'B':
System.out.println("Your favorite color is
Orange!");
break;
case 'C':
System.out.println("Your favorite color is
Green!");
break;
default:
System.out.println(
"Type A, B, or C to select a color.");
break;
}
}
}

This application begins precisely like the UseAMenu02 application does by displaying a menu of selections and asking the user to select one. In addition, it ensures that the input is converted to uppercase as needed. The switch statement compares Choice with three case clauses: A, B, and C. When Choice equals one of these constants, the application performs the task associated with that case statement and stops when it sees the break clause.

Notice especially the default: clause of the switch statement. If the user doesn’t make an appropriate choice, the code selects this option. In other words, the default: clause provides a form of error trapping. In this case, the application outputs a helpful message that reminds the user of the valid choices for the application.

3. Save the code to disk using the filename UseAMenu03.java.

4. In your command prompt, type javac UseAMenu03.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java UseAMenu03 and press Enter.

The application asks you to choose a color.

6. Type A and press Enter.

The application outputs the expected message.

7. Repeat Steps 5 and 6, but substitute a value of b this time.

The application outputs the expected message again.

8. Repeat Steps 5 and 6, but substitute a value of 3 this time.

Notice that the application now outputs a helpful message to the user, as shown in Figure 6-5.

9781118098783-fg0605.tif

Figure 6-5:

Displaying Boolean Values

This is the first chapter where you’ve really used Boolean values for their intended purpose — as decision making tools. However, you’ll still find a need to display Boolean values from time to time. Most people understand true or false, but they don’t find using true or false natural. Unfortunately, Java doesn’t provide the means for displaying Boolean values in other ways, such as outputting yes or no, words the user will understand. In the following exercise, you construct a simple method for displaying Boolean values in human-readable terms, such as yes and no.

Files needed: DisplayBoolean.java

1. Open the editor or IDE that you’ve chosen to use for this book.

2. Type the following code into the editor screen.

// Import the required API classes.
import java.lang.String;

public class DisplayBoolean
{
public static void main(String[] args)
{
// Define a Boolean value.
boolean BoolVar = true;

// Change the Boolean value into a string.
String BoolString = BoolAsString(BoolVar, "Yes", "No");

// Display the result.
System.out.println("The answer is " +
BoolString + ".");
}

public static String BoolAsString(boolean BoolValue,
String TrueString, String FalseString)
{
return BoolValue ? TrueString : FalseString;
}
}

This application creates a simple boolean named BoolVar and sets it to true. It then creates a String value named BoolString that holds a human-readable version of the BoolVar value and displays this String on screen.

The secret to this example is the BoolAsString() method, which accepts three arguments as input and returns a String value.

· BoolValue: The Boolean value that you want to convert to a string.

· TrueString: The string you want output when BoolValue is true.

· FalseString: The string you want output when BoolValue is false.

The example returns the appropriate value based on a conditional statement. You initially saw conditional statements described in the “Performing a conditional evaluation” section of Chapter 5. This example presents a practical use for a conditional statement.

3. Save the code to disk using the filename DisplayBoolean.java.

4. In your command prompt, type javac DisplayBoolean.java and press Enter.

The compiler compiles your application and creates a .class file from it.

5. Type java DisplayBoolean and press Enter.

The application outputs a human readable string that matches the BoolVar value, as shown in Figure 6-6.

9781118098783-fg0606.tif

Figure 6-6:

practice_fmt.eps Change the value of BoolVar to false. Compile and run the application. You should see the output change to match the new value of BoolVar. Try using other TrueString and FalseString values as well.

summingup_fmt.eps Summing Up

Here are the key points you learned about in this chapter:

· A conditional statement consists of a condition and a task. When the condition is true, the application performs the task.

· The condition portion of a conditional statement is also called an expression.

· Every conditional task could be performed by using a simple if statement, but using other conditional statement forms makes your application less prone to errors and also reduces the amount of typing you perform.

· The if…else statement lets your application choose between two courses of action depending on whether the expression you provide is true or false.

· Use the switch statement to allow the user to choose from a list of items.

· Rely on the default clause to provide a default action for your application when the user doesn’t provide useful input.

Try-it-yourself lab

For more practice with the features covered in this chapter, try the following exercise on your own:

1. Open the UseAMenu03 application.

2. Add a series of additional colors to the menu.

You want to change the menu to include additional System.out.println("Letter. Color"); entries. Make sure each entry has a unique letter associated with it.

3. Make the new menu entries functional by modifying the switch statement to accommodate them.

Each new color requires three lines of code similar to the code shown here:

case 'A':
System.out.println("Your favorite color is Yellow!");
break;

4. Change the default clause so that it provides the additional letters needed for the colors you added.

5. Compile the application.

6. Run the application.

7. Try each of the new menu entries.

Do the new menu entries work as you anticipated? If not, why not?

8. Try typing letters, numbers, or other symbols that don’t appear on the menu.

Does the default action still work as anticipated?

Know this tech talk

· bug: An error in the application code that causes your application to behave in a way that you didn’t anticipate.

· conditional statement: A programming construct that consists of a condition (expression) and a task. When the condition is true, the application performs the task.

· expression: A mathematical description of the condition that you want the application to check. An expression normally includes a logical operator and always provides a Boolean output.

· nesting: The act of combining multiple levels of statement into a single super statement. The application executes upper levels of the statement first and then drills down into lower levels. Use nesting to make complex decisions where one decision affects several others.