cmpt 125: lecture 4 conditionals and loopstamaras/conditionalsandloops/conditionals... · cmpt 125:...
TRANSCRIPT
CMPT 125: Lecture 4
Conditionals and Loops
Tamara Smyth, [email protected]
School of Computing Science,
Simon Fraser University
January 17, 2009
1
Flow of Control
• The order in which statements are executed is calledthe flow of control.
• Unless otherwise specified, the flow of control islinear, that is, statements are executed in the order inwhich they occur.
• Java begins a program on the first statement of themain method.
• A change in the flow of control can be accomplishedby:
– invoking a method
– conditional statements
– loops
or some combination.
CMPT 125: Conditionals and Loops, Lecture 4 2
Conditional Statements
• A conditional statement allow us to choose whichstatement will be executed next.
• Java has three conditional statements:
1. if-else
2. else if
3. switch
• These statements allow us to decide which statementto execute next based on a condition, that is, theoutcome of a boolean expression.
CMPT 125: Conditionals and Loops, Lecture 4 3
Boolean Expressions
• Recall that a boolean is a data type that evaluates toeither true or false.
• A boolean statement also evaluates to true or false,and may consist solely of a single variable, or a largerstatement involving a logical operator.
boolean hungry = false; //hungry is a boolean
if (hungry)
System.out.println(’’Let’s go eat!’’);
else
system.out.println(’’Let’s go for a drink instead.’’);
• The if statement allows a program to choosewhether to execute a particular statement.
if (num > 20)
System.out.println(’’Count is over 20.’’);
else
system.out.println(’’Count is less than or equal to 20.’’);
CMPT 125: Conditionals and Loops, Lecture 4 4
Evaluating Boolean Expressions
• Boolean expressions are evaluated using:
– equality operators:== test whether two values ARE equal!= test whether two values ARE NOT equal
– relational operators:> test whether one value is greater than another< test whether one value is less than another>= greater than or equal<= less than or equal
– logical operators:! logical NOT&& logical AND|| logical OR
• Logical operators take boolean operands
CMPT 125: Conditionals and Loops, Lecture 4 5
Logical NOT
• The logical NOT is unary, and has only two possiblevalues: true or false.
boolean hungry = false;
if (!hungry)
system.out.println(’’Let’s go for a drink instead.’’);
OUTPUT:
Let’s go for a drink instead.
• The ! is used to perform the logical NOT, or logical
complement, that is, it returns the opposite value.
boolean hungry = true;
if (!hungry)
System.out.println(’’Let’s go for a drink instead.’’);
else
System.out.println(’’Let’s go eat.’’);
OUTPUT:
Let’s go eat.
CMPT 125: Conditionals and Loops, Lecture 4 6
Logical AND, OR
• Logical AND, OR are binary operators that use twooperands, both of which are boolean.
• The result of a logical AND operation is true if andonly if both operands are true, but false otherwise.
• The result of a logical OR operation is true if one, orboth, of the operands are true, but false otherwise.
• There are four possible combinations of two logicaloperands a and b:
a b a && b a || b
false false false falsefalse true false truetrue false false truetrue true true true
CMPT 125: Conditionals and Loops, Lecture 4 7
Precedence of Operators
• Operators in order of precedence:
1. logical NOT (highest)
2. logical AND
3. logical OR
if (!done && (count > MAX))
System.out.println(‘‘Completed’’);
• To print or not to print. Let’s look at the truth table
which tells us all the possible combinations of valuesfor the variables involved.
done count > MAX !done !done && (count > MAX)
false false true false
false true true true
true false false false
true true false false
CMPT 125: Conditionals and Loops, Lecture 4 8
Example code using if-else, else if
public class testNum
{
public static void main(String[] args)
{
int num = Integer.parseInt(args[0]);
if (num > 5)
System.out.println(num + " > 5");
else if (num > 4)
System.out.println(num + " > 4");
else if (num > 2)
System.out.println(num + " > 2");
else
System.out.println(num + " is 2 or less");
}
}
CMPT 125: Conditionals and Loops, Lecture 4 9
Short Circuiting Operations
• The AND and OR operators may be “short-circuited”meaning that is the left operand is sufficient to decidethe boolean result, the right operand is not evaluated.
• You can use this to your advantage by ensuringvariables will not result in an expression that isundefined, e.g. preventing a division by zero.
if (count != 0 && total/count > MAX)
System.out.println(‘‘Testing’’);
• An equivalent way of achieving the same result wouldinvolve nesting the if statements:
if (count != 0)
if (total/count > MAX)
System.out.println(‘‘Testing’’);
CMPT 125: Conditionals and Loops, Lecture 4 10
Block Statement
• An if statement consists of the reserved word if
followed by a boolean expression, followed by one ormore statements. That is, a single statement can bereplaced with a block statement, a collection ofstatements enclosed in braces.
if (guess == answer)
System.out.println(‘‘You’re right!’’);
else
{
System.out.println(‘‘I’m sorry.’’);
System.out.println(‘‘The correct answer is ’’ + answer);
}
• It is common practice, and very important to thehuman reader, to indent the statement(s) followingthe boolean expression to show they are part of theif statement.
CMPT 125: Conditionals and Loops, Lecture 4 11
A Loop, or Repetitive Statement
• A loop, or repetitive statement, allows us to execute aprogramming statement more than once.
• Like a conditional, a loop is based on the evaluationof a boolean expression
• Java has three loop statements:
1. while
2. do
3. for
CMPT 125: Conditionals and Loops, Lecture 4 12
The while Statement
• A while statement is followed by a booleanexpression, and evaluates a statement, or a block ofcode, repeatedly, while the condition remains true.
public static void main(String[] args)
{
int sum = 0, value, count = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer (0 to quit): ");
value = scan.nextInt();
while(value != 0)
{
count++;
sum += value;
System.out.println("The sum so far is " + sum);
System.out.println("Enter an integer (0 to quit): ");
value = scan.nextInt();
}
if (count==0)
System.out.println("No values were entered.");
else
{
DecimalFormat fmt = new DecimalFormat("0.###");
System.out.println("The average is "
+ fmt.format((double)sum/count));
}
}
• Avoid infinite loops!
CMPT 125: Conditionals and Loops, Lecture 4 13
The Conditional Operator
• When using the conditional operator, a booleancondition is followed by the ? operator which isfollowed by two expressions separated by the :
operator.
: 2nd expressionboolean condition ? 1st expression
Figure 1: The conditional operator.
• The first of the two expression is evaluated if theboolean condition is true, and if false, the secondexpression is evaluated.
• The following is an example use of the conditionaloperator
• A ternary operator because it requires three operands.
(total > MAX) ? total + 1 : total * 2;
• The Conditional operator returns a value, andtherefore might be used as follows:
total = (total > MAX) ? total + 1 : total * 2;
CMPT 125: Conditionals and Loops, Lecture 4 14
Comparing Floats
• Two floating point values are equal, according to the== operator, only if all the binary digits of theirunderlying representations match.
• Since this is unlikely to be the case (perhaps due torounding errors), it is best not to use this operator forcomparing floating point values.
• A better way computes the absolute value of thedifference between the two, and then compare theresult to some tolerance level.
if (Math.abs(f1-f2) < TOLERANCE)
System.out.println(‘‘Effectively equal.’’);
CMPT 125: Conditionals and Loops, Lecture 4 15
Comparing Characters
• Equality and relational operators may also be used oncharacter data.
• Because of the Unicode character set, it is possible todetermine if one is less than another.
if (ch1 > ch2)
System.out.println(ch1 + ‘‘ is greater than ‘‘ + ch2);
else
System.out.println(ch1 + ‘‘ is NOT greater than ‘‘ + ch2);
CMPT 125: Conditionals and Loops, Lecture 4 16
Comparing Objects
• The String class contains an equals method thatreturns true if two strings have exactly the samecharacters, and false otherwise.
if (name1.equals(name2))
System.out.println(‘‘The names are the same.’’);
else
System.out.println(‘‘The names are NOT the same.’’);
• It is valid to test two String objects using using theequality operator, but it will test whether theyreference the same object:
String name1 = new String(‘‘string’’);
String name2 = new String(‘‘string’’);
if (name1 == name2)
System.out.println(‘‘These variables contain ‘‘ +
‘‘the same address.’’);
else
System.out.println(‘‘These variables contain ‘‘ +
‘‘different addresses.’’);
OUTPUT:
These variables contain different addresses.
CMPT 125: Conditionals and Loops, Lecture 4 17
The switch Statement
• The switch statement evaluates an expression todetermine a value.
• It then matches that value with one of severalpossible cases.
switch(grade)
{
case ’A’:
System.out.println(‘‘Excellent Work!’’);
break;
case ’B’:
System.out.println(‘‘Good Work.’’);
break;
case ’C’:
System.out.println(‘‘Satisfactory Work.’’);
break;
default:
System.out.println(‘‘Error in identifying your grade!’’);
}
• If no case matches the evaluated expression,execution continues with the default case.
• When a break statement is encountered, theprogram exits the switch statement, and continueswith the next statement.
CMPT 125: Conditionals and Loops, Lecture 4 18
Nested Loops
• The body of a loop can contain another loop.
public class Palindrome
{
public static void main(String[] args)
{
String str, another = "y";
int left, right;
Scanner scan = new Scanner(System.in);
while(another.equalsIgnoreCase("y"))
{
System.out.println("Enter a palindrome");
str = scan.nextLine();
left = 0;
right = str.length() - 1;
while(str.charAt(left) == str.charAt(right) &&
left < right)
{
left++;
right--;
}
System.out.println();
if (left<right)
System.out.println("The string is NOT a palindrome.");
else
System.out.println("The string IS a palindrome.");
System.out.print("Test another palindrome (y/n)?");
another = scan.nextLine();
}
}
CMPT 125: Conditionals and Loops, Lecture 4 19
Iterators
• An iterator is an object that has methods that allowyou to process a collection of items one at a time.
• Since it is a repetitive process, it is related to loops.
• An iterator in Java is defined using the Iterator
interface.
• The Scanner class has methods such as hasNext,hasNextInt, hasNextDouble, to determine if thenext input token is of a particular type.
• The Scanner class as an iterator is useful whenprocessing a data file or processing parts of acharacter string.
• A delimiter is used to separate tokens in a Scanner
object.
fileScan.useDelimeter(‘‘;’’);
CMPT 125: Conditionals and Loops, Lecture 4 21
The do statement
• The do loop executes the statement in the loop untilthe condition, written at the end of of the loop,becomes false.
int count = 0;
do
{
count++;
System.out.println(count);
} while (count < 5);
• A do statement executes its loop body at least once.This may give you reason to choose a do, rather thana while loop.
CMPT 125: Conditionals and Loops, Lecture 4 22
The for statement
• The do and while loops are usually used when youdon’t know exactly how many times you want toexecute the loop body.
• The for loop is suited to situations where you knowprecisely how many times the loop should beexecuted.
for (int count = 0; count < 10; count++)
System.out.println(count);
• The header of a for loop contains three partsseparated by semicolons:
1. initialization: executed before the loop begins.
2. boolean condition: evaluated before the loopbody; if true the loop is executed.
3. increment: executed after each loop iteration.
• It is also possible to decrement a value:
for (int count = 10; count > 0; count--)
System.out.println(count);
CMPT 125: Conditionals and Loops, Lecture 4 23
Iterators and for loops
• A variation of the for loop lets us process the itemsin an iterator with a different syntax. Consider theiterator Booklist that manages Book objects:
for(Book myBook : BookList)
System.out.println(myBook);
is equivalent to
Book mybook;
while (BookList.hasNext())
{
myBook = BookList.next();
System.out.println(myBook);
}
• This version can also be used on arrays.
CMPT 125: Conditionals and Loops, Lecture 4 24