© Adam L. Davis 2020
A. L. DavisModern Programming Made Easyhttps://doi.org/10.1007/978-1-4842-5569-8_6

6. Conditionals and Loops

Adam L. Davis1 
(1)
Oviedo, FL, USA
 

To rise above the label of calculator, a programming language must have conditional statements and loops.

A conditional statement is a statement that may or may not execute, depending on the circumstances.

A loop is a statement that gets repeated multiple times.

If, Then, Else

The most basic conditional statement is the if statement . It executes some code only if a given condition is true. It is the same in all languages covered in this book. For example:
1   if (vampire) { // vampire is a boolean
2           useWoodenStake();
3   }
Curly brackets ({}) define a block of code (in Java, Scala, Groovy, and JavaScript). To define what should happen if your condition is false, you use the else keyword.
1   if (vampire) {
2           useWoodenStake();
3   } else {
4           useAxe();
5   }
Actually, this can be shortened, because in this case we only have one statement per condition.
1   if (vampire) useWoodenStake();
2   else useAxe();
It’s generally better to use the curly bracket style in Java to avoid any accidents later on when another programmer adds more code. If you have multiple conditions you have to test, you can use the else if style, such as the following:
1   if  (vampire) useWoodenStake();
2   else if (zombie) useBat();
3   else useAxe();

Switch Statements

Sometimes you have so many conditions that your else if statements span several pages. In this case, you might consider using the switch keyword . It allows you to test for several different values of the same variable. For example:
1   switch (monsterType) {
2   case "Vampire": useWoodenStake(); break;
3   case "Zombie": useBat(); break;
4   case "Orc": shoutInsult();
5   default: useAxe();
6   }

The case keyword denotes the value to be matched.

The break keyword always causes the program to exit the current code block. This is necessary in a switch statement; otherwise, every statement after the case will be executed. For example, in the preceding code, when monsterType is "Orc", both shoutInsult and useAxe are executed because there is no break after shoutInsult().

The default keyword denotes the code to execute if none of the other cases are matched. It is much like the final else block of an if/else block.

../images/435475_2_En_6_Chapter/435475_2_En_6_Figa_HTML.jpg There is more to switch statements, but this involves concepts we’ll cover later on, so we’ll return to this topic.

../images/435475_2_En_6_Chapter/435475_2_En_6_Fig1_HTML.jpg
Figure 6-1

Formal Logic—XKCD 1033 (courtesy http://​xkcd.​com/​1033/​)

Boolean Logic

Computers use a special kind of math called Boolean logic (it’s also called Boolean algebra ). All you really need to know are the following three Boolean operators and six comparators. The operators first:
  • && — AND: true only if left and right values are true

  • || — OR: true if either left or right value is true

  • ! — NOT: Negates a Boolean (true becomes false; false becomes true)

Now the comparators:
  • == — Equal: True if both values are equal.

  • != — Not Equal: The left and right values are not equal.

  • < — Less than: The left side is less than the right.

  • > — Greater than: The left side is greater than the right.

  • <= — Less than or equal.

  • >= — Greater than or equal.

Conditions (such as if) operate on Boolean values (true/false)—the same boolean type that you learned about in Chapter 3. When used properly, all the preceding operators result in a Boolean value.

For example:
1   if (age > 120 && skin == Pale && !wrinkled) {
2           probablyVampire();
3   }

Looping

The two simplest ways to loop are the while loop and do/while loop.

The while loop simply repeats while the loop condition is true. The while condition is tested at the start of each run of the loop.
1   boolean repeat = true;
2   while (repeat) {
3           doSomething();
4           repeat = false;
5   }

The preceding would call the doSomething() method once. The loop condition in the preceding code is repeat. This is a simple example. Usually, the loop condition would be something more complex.

The do loop is like the while loop, except that it always goes through at least one time. The while condition is tested after each run through the loop. For example:
1   boolean repeat = false;
2   do  {
3           doSomething();
4   } while(repeat);
It’s often helpful to increment a number in your loop, for example:
1   int i = 0;
2   while (i < 10) {
3           doSomething(i);
4           i++;
5   }
The preceding loop, which loops ten times, can be condensed using the for loop as follows:
1   for  (int  i = 0; i < 10; i++) {
2           doSomething(i);
3   }
The for loop has an initiation clause, a loop condition, and an increment clause. The initiation clause comes first (int i = 0 in the preceding loop) and is only called once before the loop is run. The loop condition comes next (i < 10) and is much like a while condition. The increment clause comes last (i++) and is called after each loop execution. This style of loop is useful for looping through an array with an index. For example:
1   String[] strArray = {"a", "b", "c"};
2   for (int i = 0; i < strArray.length; i++)
3           System.out.print(strArray[i]);
This would print “abc.” The preceding loop is equivalent to the following:
1   int i = 0;
2   while  (i < strArray.length) {
3       String str = strArray[i];
4           System.out.print(str);
5           i++;
6   }
In Java, you can write for loops in a more concise way for an array or collection (list or set). For example:
1   String[] strArray = {"a", "b", "c"};
2   for  (String str : strArray)
3             System.out.print(str);

This is called a for each loop . Note that it uses a colon instead of a semicolon.

Summary

In this chapter, you learned about the following:
  • Using the if statement

  • How to use Boolean logic

  • switch statements

  • Using for, do, while, and for each loops

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset