Decisions
Nothing is more difficult,
and therefore more precious, than to be able to decide.
-- Napoleon
Bonaparte
I have always wished that my computer would be as easy
to
use as my telephone. My wish has come true. I no longer know
how to use my telephone.
--Bjarne Stroustrup (originator of C++ programming language)
Review Exercise: Given a String
variable myString which has already
been initialized, declare a String variable part and
assign it to contain the string consisting of the first 5 characters in
myString.
To Execute or not to Execute (a Statement), that is the question.
A conditional
statement
allows us to choose which statement in our program will be executed
next.
Example:
if (it is raining)
Carry an umbrella
The expression - the condition - inside the parentheses is either true
or false.
- If it is
true, then we will execute the next statement, which says to carry an
umbrella.
Java Example:
if(grade > 95)
{
System.out.println("You made a high A!");
}
Again the condition, or expression inside the parentheses, is a boolean
value - it is either true or false.
- If it is true, the statement "You
made a high A!" will be displayed in the console window.
- If it is false, then the next statement after the body
of the if is executed.
Example:
int theAreaCode = 512;
...
if(theAreaCode = = 512)
{
System.out.println("You live in Texas");
}
- In conditional expressions, we often want to compare
two
values. The = = operator compares two numeric values for equality.
- Remember that = is used for assignment, not comparison.
Relational Operators
- The result of a relational operator is boolean - either
true or false.
The relational operators:
less than (<), greater than (>), less than or equal (<=),
greater than or equal (>=), equal (==), not equal (!=)
Examples:
boolean test = (13 > 15); // is test true or false?
boolean test2 = (101 >= 99); // true or false?
boolean test3 = (13 == 13); // true or false?
Logical Operators
- logical operators can be applied to boolean values only
- the result is a boolean
The logical operators:
AND (&&)
OR (||)
NOT (!)
- p && q is true only when both p and q are true.
Otherwise p
&& q is false.
- p || q is true when at least one of p and q is true. If
p and q are
both false, then p|| q is false.
- !p is false if p is true, and !p is true if p is false.
Examples:
int i = 14;
int j = 18;
char c1 = 'e';
char c2 = 'h';
System.out.println("i<j is " + (i<j)); // output: i<j is true
System.out.println("i < j && i == i is " + ((i < j)
&& (i == i))); // output?
boolean test = !(i < j); // test is true or false?
boolean test2 = (c1 == c2); // test2 is true or false?
boolean test3 = (i<j) || (c1>c2); // true or false?
boolean test4 = (i<j) && (c1 > c2);
Note about Strings
- Since String variables are references, they cannot be
compared
for equality using the == operator.
- == only determines if two Strings are stored in the
same memory
location.
Instead, use the equals() method to determine if 2 Strings are the same:
String h = "hello";
boolean test = h.equals("hello"); // test is true
boolean test2 = "hello".equals(h); // test2 is true
The if statement
Syntax:
if(expression)
{
// body of if
}
- The expression is evaluated, and if it is true, then
the body is
executed. Otherwise the body of the if statement is not executed.
Example:
int numberOfBags = 3;
...
if(numberOfBags > 2)
{
System.out.println("You can only carry on 2 pieces of
luggage");
}
Note: When the body of the if
statement is only one statement, the curly
braces can be omitted:
if(numberOfBags > 2)
System.out.println("You can only carry on 2 pieces of
luggage");
The if-else statement
Syntax:
if(expression)
{
// action1
}
else
{
// action2
}
When an if-else is executed, the expression is evaluated first. If the
expression is true, then action1 is executed. Otherwise action2 is
executed.
Examples:
int num = 28;
...
if ((num % 4) = = 0)
System.out.println(num + " is divisible by 4");
else
System.out.println(num + " is not divisible by 4");
Important Note
about Comparing Floating-Point Numbers
- Floating-point numbers have limited precision.
- Calculations lead to
roundoff errors.
Consider the following code:
double root = Math.sqrt(2);
double diff = root*root - 2; // we expect diff to be 0
if(diff == 0)
System.out.println("sqrt(2)^2 - 2 is 0");
else
System.out.println("sqrt(2)^2 - 2 is " + diff);
Output:
sqrt(2)^2 - 2 is 4.440892098500626E-16
You should compare whether floating-point numbers are "close enough",
rather than exactly equal. Roundoff errors are unavoidable.
Exercise: Write a program that
reads two floating-point numbers from
the keyboard, and prints a message indicating whether they are within
epsilon of each other, where epsilon is the program-defined
constant 0.0001.
Exercise: Write a program that
reads a string from the keyboard, and
prints a message indicating whether or not each of the vowels a, e, i,
o and u occur in the string.
Exercise: Write a program that
reads 2 strings from the keyboard, and
indicates whether or not they are the same string. Then edit the
program to indicate whether or not the strings are the same if
differences in case are disregarded.
The
if - else if - else statement
Syntax:
if(expression1)
{
// action1 - execute this code if expression1 is true
}
else if(expression2)
{
// action2 - execute this code if expression1 is false and
expression2 is true
}
else
{
// action3 - execute this code if expression1 and
expression2 are both false
}
How it works:
Expression1 is evaluated, and if it is true, action1 is executed. If
expression1 is false and expression2 is true, then action2 is executed.
If expression1 and expression2 are both false, then action3 is executed.
Example:
if(examGrade >= 90)
System.out.println("A");
else if(examGrade >= 80)
System.out.println("B");
else if(examGrade >= 70)
System.out.println("C");
else if(examGrade >= 60)
System.out.println("D");
else
System.out.println("F");
The switch statement
Syntax:
switch(expression)
{
case val1:
// action1 - execute if the
value of expression is val1
break;
case val2:
// action2 - execute if the
value of expression is val2
break;
case val3:
// action3 - execute if the
value of expression is val3
break;
...
default:
//defaultAction - execute if
expression did not match any of above vals
break;
}
How it works:
If the value of expression is vali,
then actioni is executed. The
default case is optional, but if it is included and expression does not
match any vali, then the
defaultAction is executed.
Important
note: The expression must be of type int or char.
Example:
int k;
...
switch(k)
{
case 0: System.out.println("zero"); break;
case 1: System.out.println("one"); break;
case 2: System.out.println("two"); break;
case 3: System.out.println("three"); break;
default: System.out.println("integer is not in [0, 3]");
break;
}
Processing Characters
Static methods from java.lang.Character
class:
- isDigit() - returns true if the character passed in is
a digit, false otherwise
- isLetter() - returns true if the character passed in is
a letter, false otherwise
- isLetterOrDigit() - returns true if the character
passed in is a letter or digit
- isLowerCase() - returns true if the character passed in
is lowercase, false otherwise
- isUpperCase() - returns true if character is uppercase,
false otherwise
- isWhitespace() - returns true if character is
whitespace, false otherwise
- toLowerCase() - returns the lowercase version of the
character that is passed in
- toUpperCase() - returns the uppercase version of the
character that is passed in
Example:
String word = ...;
if(Character.isDigit(word.charAt(0)))
{
System.out.println(word + " cannot be a Java
identifier, since identifiers do not
start with a digit");
}
Example:
String name = ...;
// print name with the first letter capitalized
char firstLetter = name.charAt(0);
char capitalFirst = Character.toUpperCase(firstLetter);
System.out.println(capitalFirst + name.substring(1));
Exercise: Go back and revise
the code in the above example so that it handles the cases where the
length of name is either 0 or 1 correctly.
Exercise: Finish the println()
call to print an appropriate message.
String s;
...
// asume s has been initialized
if(Character.isLetterOrDigit(s.charAt(s.length()-1)))
System.out.println(
)
More on Comparing Strings
Recall:
- The equals() method in the String class
returns true if the
two strings being compared are the same, and false otherwise.
- Comparing two String variables with the =
= operator just
tells you if the reference variables refer to the same String object or
not (i.e. contain the same memory address).
The compareTo() method in the String
class:
- determines the
relative order of strings.
- the method returns an
integer: the return value is
- negative if the String on which the
method is called is less
than the String passed in
- 0 if the two Strings are the same
- positive if the String on which the method is called
is greater than the String passed in
Note:
If all letters are the same case, then the lexicographic
ordering provided by the compareTo() method is the same as alphabetic
order. Otherwise remember that in the Unicode character set, all
uppercase letters come before all lowercase letters. So "Battle" comes
before "ant".
Example:
String name1;
String name2;
...
// assume the String variables are initialized
int cmpValue = name1.compareTo(name2);
if(cmpValue < 0)
System.out.println(name1 + " precedes " + name2);
else if (cmpValue = = 0)
System.out.println(name1 + " equals " + name2);
else
System.out.println(name1 + " comes after " + name2);
Exercise: Write a program that
reads a word from the keyboard. If the
first character is a vowel, print a message indicating which vowel
occurs at the beginning of the word. Otherwise print a message
indicating that the word does not begin with a vowel.
Exercise: Write a program that
reads a string from the keyboard. If the
string is the empty string, print a message indicating that the string
is empty. If the first character is white space, remove all leading and
trailing blanks and print the resulting string. If the first character
is a letter, print the string with this first letter capitalized. If
the first character is a number, just print the string to the screen.
Exercise: Write a program that
reads a word from the keyboard. If the
length of the word is not 3, print a message indicating that the word
must be of length 3. Otherwise, determine if the word is a palindrome
(ie a word that reads the same left to right and right to left).
Iteration
Structures
The while statement
Example:
while(hungry)
{
eat another bite
}
Example:
while(there are more lines of text in the input file)
{
read the next line from the file
}
Syntax:
while(expression)
{
statement(s)
}
How it works:
A while statement executes a block of code repeatedly, as long as the
associated expression is true. The expression is evaluated before each
execution of the statements in the while body, and if the expression
evalutes to false, execution of the while loop terminates.
Example:
int count = 1;
while(count <= 5)
{
count++;
}
System.out.println("count is " + count);
Example:
// initialize variables to use in loop
int num = 1;
int sum = 0;
// as long as num is at most 5, add num to the sum
while(num <= 5)
{
sum = sum + num; // add the current value of num to
the sum
num++; // don't forget to update num - what
happens if I omit this statement??
}
System.out.println("The sum of the first 5 positive integers is " +
sum);
Exercise: Write a program that
prints the integers from 1 to 15 to the console window, one number per
line.
The
for statement
Example:
// initialize numPets to 0
// while numPets is at most 3, adopt a pet.
// After each adoption, increment numPets.
for(set numPets to 0; numPets
<= 3;
add 1 to numPets)
{
adopt a pet from the humane society
}
Syntax:
for(init; expression; update)
{
// Action -
execute this code as long as the expression is true. After executing
// the loop body, execute the update statement(s).
}
How it works:
- First the init
is executed.
It is only executed once.
- Next, the expression
is
evaluted.
- It it is false, execution proceeds to the
statement following
the for loop.
- If expression
is true, then the Action is
executed and then the update
is executed.
- The process
repeats as long as the expression
is true.
Example:
// initialize the sum to 0
int sum = 0;
// compute the sum of the numbers between 1 and 5
for(int i = 1; i <=5; i++)
{
sum = sum + i;
}
System.out.println("The sum of the first 5 positive integers is " +
sum);
Exercise: Write a for loop that prints all the integers from -10 to 10
to
the console window.
Exercise: Write a program that reads a positive integer n from the
keyboard,
and prints the sum of the first n positive integers.
Exercise: Write a program that reads 20 integers from the keyboard, and
then prints a message indicating how many of them were positive,
negative, and zero.
The do-while statement
If you want to execute the body of a loop at least once, you might use
a do-while loop.
Syntax:
do
{
// body of do-while loop
}
while (condition) ;
How it works:
The body of the loop is executed, and then the condition is evaluated.
If the condition is true, the body is executed, and this process
repeats.
Example:
do
{
start the car's engine
}
while(engine is not running);
Example:
// initialize the loop variables
int val = 5;
// what does this loop do?
do
{
System.out.println(val);
val--;
}
while((val+1)> 0);
Output?
Nested
Loops
Example: Write a program that
prints the following triangle to the console window.
*
**
***
****
*****
******
*******
********
*********
**********
Idea: Use a loop - each
iteration of the loop should print one row of
the triangle.
for(int i = 1; i <= 10; i++)
{
// add code that prints a row of i *'s
System.out.println(); // skip to next row
}
Now: How do we print a row with
i *'s in it?? With a loop:
for(int j = 1; j <= i; j++)
{
System.out.print("*");
}
Complete Solution:
// print a triangle with 10 rows
for(int i = 1; i <= 10; i++)
{
// print a row of length i, where each row entry is
an *
for(int j = 1; j <= i; j++)
{
System.out.println("*");
}
// skip to next row
System.out.print("\n");
}