Docsity

Conditionals - Computer Programming and Problem Solving | CS 111, Assignments of Computer Science

Toggle sidebar
bg1
Chapter 4
Conditionals
4.1 Floating-point
There is only one problem with the integer arithmetic we have been using—no
fractions. The solution is floating-point numbers, which can represent fractions
as well as integers. In Java, the floating-point type is called double (short for
double-precision floating-point).
You can create floating-point variables and assign values to them using the
same syntax we used for the other types. For example:
double pi;
pi = 3.14159;
Of course, you can also declare the variable and assign a value at the same time:
int x = 1;
double pi = 3.14159;
Although doubles are useful, they are sometimes a source of confusion because
there seems to be an overlap between integers and floating-point numbers. For
example, if you have the value 1, is that an integer, a floating-point number, or
both?
Strictly speaking, Java distinguishes the integer value 1from the floating-
point value 1.0, even though they seem to be the same number. They belong
to different types, and you are not allowed to make assignments between types.
For example, the following is illegal:
int x = 1.1;
because the variable on the left is an int and the value on the right is a double.
But it is easy to forget this rule, especially because there are places where Java
will automatically convert from one type to another. For example,
double y = 1;
35
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Conditionals - Computer Programming and Problem Solving | CS 111 and more Assignments Computer Science in PDF only on Docsity!

Chapter 4

Conditionals

4.1 Floating-point

There is only one problem with the integer arithmetic we have been using—no fractions. The solution is floating-point numbers, which can represent fractions as well as integers. In Java, the floating-point type is called double (short for double-precision floating-point). You can create floating-point variables and assign values to them using the same syntax we used for the other types. For example:

double pi; pi = 3.14159;

Of course, you can also declare the variable and assign a value at the same time:

int x = 1; double pi = 3.14159;

Although doubles are useful, they are sometimes a source of confusion because there seems to be an overlap between integers and floating-point numbers. For example, if you have the value 1 , is that an integer, a floating-point number, or both? Strictly speaking, Java distinguishes the integer value 1 from the floating- point value 1.0, even though they seem to be the same number. They belong to different types, and you are not allowed to make assignments between types. For example, the following is illegal:

int x = 1.1;

because the variable on the left is an int and the value on the right is a double. But it is easy to forget this rule, especially because there are places where Java will automatically convert from one type to another. For example,

double y = 1;

36 CHAPTER 4. CONDITIONALS

should technically not be legal, but Java allows it by converting the int to a double automatically. This leniency is convenient, but it can cause problems; for example:

double y = 1 / 3;

You might expect the variable y to be given the value 0.333333, which is a legal floating-point value, but in fact it will get the value 0.0. The reason is that the expression on the right is the ratio of two integers, so Java does integer division, which yields the integer value 0. Converted to floating-point, the result is 0.0. One way to solve this problem (once you figure out what it is) is to make the right-hand side a floating-point expression:

double y = 1.0 / 3.0;

This sets y to 0.333333, as expected. All the operations we have seen so far—addition, subtraction, multiplica- tion, and division—also work on floating-point values, although you might be interested to know that the underlying mechanism is completely different. In fact, most processors have special hardware just for performing floating-point operations.

4.2 Converting from double to int

As I mentioned, Java converts ints to doubles automatically if necessary, be- cause no information is lost in the translation. On the other hand, going from a double to an int requires rounding off. Java doesn’t perform this operation automatically, in order to make sure that you, as the programmer, are aware of the loss of the fractional part of the number. The simplest way to convert a floating-point value to an integer is to use a typecast. Typecasting is so called because it allows you to take a value that belongs to one type and “cast” it into another type (in the sense of molding or reforming, not throwing). The syntax for typecasting is ugly: you put the name of the type in paren- theses and use it as an operator. For example,

int x = (int) 3.14159;

The (int) operator has the effect of converting what follows into an integer, so x gets the value 3. Typecasting takes precedence over arithmetic operations, so in the following example, the value of pi gets converted to an integer first, and the result is 60, not 62.

double pi = 3.14159; int x = (int) Math.PI * 20.0;

38 CHAPTER 4. CONDITIONALS

int fred = 3;

// and then later ...

int fred = 5;

This code is illegal because it tries to declare (and create) the variable fred twice. After the initial declaration, all subsequent assignments omit the variable type.

4.4 Conditional execution

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:

if (x > 0) { System.out.println ("x is positive"); }

The expression in parentheses is called the condition. If it is true, then the statements in brackets get executed. If the condition is not true, nothing hap- pens. The condition can contain any of the comparison operators:

x == y // x equals y x != y // x is not equal to y x > y // x is greater than y x < y // x is less than y x >= y // x is greater than or equal to y x <= y // x is less than or equal to y

Although these operations are probably familiar to you, the syntax Java uses is a little different from mathematical symbols like =, 6 = and ≤. A common error is to use a single = instead of a double ==. Remember that = is the assignment operator, and == is a comparison operator. Also, there is no such thing as =< or =>. The two sides of a condition have to be the same type, so we can only compare int to int and double to double. You cannot use the comparison operators on objects, so there is no way to know which of two Buggles is greater.

4.5 Alternative execution

A second form of conditional execution is alternative execution in which there are two possibilities, and the condition determines which one gets executed. The syntax looks like:

4.6. CHAINED CONDITIONALS 39

if (x > 0) { System.out.println ("x is positive"); } else { System.out.println ("x is negative or zero"); }

If the condition is true, that means that x is positive, and this code prints a message to that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or false, exactly one of the alterna- tives will be executed.

4.6 Chained conditionals

Sometimes you want to check for a number of related conditions and choose one of several actions. One way to do this is by chaining a series of ifs and elses:

if (x > 0) { System.out.println ("x is positive"); } else if (x < 0) { System.out.println ("x is negative"); } else { System.out.println ("x is zero"); }

These chains can be as long as you want, although they can be difficult to read if they get out of hand. One way to make them easier to read is to use standard indentation, as demonstrated in these examples. If you keep all the statements and squiggly-brackets lined up, you are less likely to make syntax errors and you will find them more quickly if you do.

4.7 Nested conditionals

In addition to chaining, you can also nest one conditional within another. We could have written the previous example as:

if (x == 0) { System.out.println ("x is zero"); } else { if (x > 0) { System.out.println ("x is positive"); } else { System.out.println ("x is negative"); } }

4.10. BOOLEAN METHODS 41

positiveFlag || x<0 == 0 is true if either of the conditions is true, that is, if positiveFlag is true OR x is less than zero. Finally, the NOT operator has the effect of negating or inverting a boolean expression, so !positiveFlag is true if positiveFlag is false. Logical operators often provide a way to simplify nested conditional state- ments. For example, how would you write the following code using a single conditional?

if (x > 0) { if (x < 10) { System.out.println ("x is a positive single digit."); } }

4.10 Boolean methods

Methods can return boolean values just like any other type. The Buggle class includes several boolean methods:

public boolean isBrushDown () Return true if this Buggle will leave a trail when it moves, false otherwise. public boolean isOverBagel () Returns true if there is a bagel in the cell currently occupied by this buggle, false otherwise. public boolean isFacingWall () Returns true if this buggle is next to a wall of Buggle world and facing it, false otherwise. It is common to give boolean methods names that sound like yes/no ques- tions. These methods are useful for checking whether an operation is possible before trying it. For example:

if (becky.isOverBagel ()) { becky.pickUpBagel (); }

You can write your own boolean methods. For example, Buggles do not provide a method named isBrushUp, but you could write your own.

public boolean isBrushUp () { if (isBrushDown() == true) { return false; } else { return true; } }

42 CHAPTER 4. CONDITIONALS

The return type is boolean, which means that every return statement has to provide a boolean expression. This code is nice and readable, although it is a bit longer than it needs to be. The return value from the original method, isBrushDown, has type boolean, so all we have to do is apply the NOT operator.

public boolean isBrushUp () { return !isBrushDown (); }

Here is a more interesting boolean method. It checks whether there is a bagel on the square one step in front of the Buggle.

public boolean isBagelInFront () { if (isFacingWall ()) { return false; } else { forward (); boolean result = isOverBagel (); backward (); return result; } }

There are two (slightly) tricky things here. One is the first branch of the con- ditional. If we are facing a wall, then we know there is no bagel there. In that case we can return false immediately. This kind of check is sometimes called a special case. In the common case, all we have to do is move forward (which we now know is safe) and check for a bagel. The second tricky thing is that we have to store the result temporarily because we have to move the Buggle back before we get to the return statement. The following code changes the state of the brush from up to down or down to up:

if (becky.isBrushDown ()) { becky.brushUp (); } else { becky.brushDown (); }

Flipping a boolean value like this is called toggling.

4.11 Variables inside conditionals

A variable declared inside an if statement only exists inside the if statement.

44 CHAPTER 4. CONDITIONALS

4.12 Glossary

typecast: Convert a value from one type to another.

conditional statement: Any of the forms of an if statement that execute statements (or not) depending on the result of a boolean expression.

alternative execution: A conditional statement with two branches, an if branch and an else branch, exactly one of which will be executed.

chaining: A way of organizing a string of consecutive conditional statements.

nested structure: In general, the ability to nest one statement within another. In the context of conditional statements, nesting is one way of organizing a set of conditional statements.

comparison operators: Any of the operators that compare values and pro- duce boolean values.

boolean: A primitive type in Java, made up of the values true and false.

flag: A boolean variable that record the result of a condition operator to “flag” a condition.

logical operators: The operators AND, OR, and NOT, which are used to combine boolean expressions.

special case: A part of a program that handles unusual conditions that cannot be handled by the general case.

general case: A part of a program that handles the most common and exten- sive set of conditions.

toggle: To flip the state of a boolean variable from false to true and vice versa.