0% found this document useful (0 votes)
78 views39 pages

If Statement: If (Amount Balance) Balance Balance - Amount

The document discusses various Java control flow statements including if/else statements, while loops, do-while loops, for loops, and nested loops. It provides examples of how to use these statements and common errors to avoid such as off-by-one errors and infinite loops. It also covers comparing different data types like floating-point numbers, strings, and objects as well as reading input values.

Uploaded by

Chintan Manek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views39 pages

If Statement: If (Amount Balance) Balance Balance - Amount

The document discusses various Java control flow statements including if/else statements, while loops, do-while loops, for loops, and nested loops. It provides examples of how to use these statements and common errors to avoid such as off-by-one errors and infinite loops. It also covers comparing different data types like floating-point numbers, strings, and objects as well as reading input values.

Uploaded by

Chintan Manek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 39

if Statement

if (amount <= balance)


balance = balance - amount;

if/else Statement
if (amount <= balance)
balance = balance - amount;
else
balance = balanceOVERDRAFT_PENALTY;

Block Statement
if (amount <= balance)
{
double newBalance = balance - amount;
balance = newBalance;
}
Note: block allows more than one statement
to be combined, to form a new statement

Equality Testing vs. Assignment


The = = operator tests for equality:
if (x = = 0) . . // if x equals zero
The = operator assigns a value to a variable:
x = 0; // assign 0 to x
Don't confuse them.
Java = = is the same as mathematical =

Comparing Floating-Point
Numbers
Consider this code:
double r = Math.sqrt(2);
double d = r * r -2;
if (d == 0)
System.out.println(
"sqrt(2)squared minus 2 is 0");
else
System.out.println(
"sqrt(2)squared minus 2 is not 0 but " + d);

It prints:
sqrt(2)squared minus 2 is not 0 but
4.440892098500626E-16
Don't use == to compare floating-point
numbers

Comparing Floating-Point
Numbers
Two numbers are close to another if
|x - y| <=
is a small number such as 10-14
Not good enough if x, y very large or very small.
Then use
|x - y| / max(|x|, |y|) <=
But if one of the numbers is zero, don't divide by
max(|x |, |y|)

String Comparison
Don't use = = for strings!
if (input = = "Y") // WRONG!!!
Use equals method:
if (input.equals("Y"))
= = tests identity, equals tests equal contents
Case insensitive test ("Y" or "y")
if (input.equalsIgnoreCase("Y"))

Lexicographic Comparison
s.compareTo(t) < 0 means:
s comes before t in the dictionary
"car"comes before "cargo"
"cargo" comes before "cathode"
All uppercase letters come before lowercase:
"Hello" comes before "car"

Lexicographic Comparison

Object Comparison

= = tests for identical object


equals for identical object content
Rectangle cerealBox = new
Rectangle(5, 10, 20, 30);
Rectangle oatmealBox = new
Rectangle(5, 10, 20, 30);
Rectangle r = cerealBox;
cerealBox != oatmealBox,
but cerealBox.equals(oatmealBox)
cerealBox == r
Caveat: equals must be defined for the class (chap 11)

Object Comparison

The null Reference


null reference refers to no object at all
Can be used in tests:

if (account == null) . . .

Use ==, not equals, to test for null


showInputDialog returns null if the user hit the cancel
button:
String input = JOptionPane.showInputDialog("...");
if (input != null) { ... }
null is not the same as the empty string ""

Multiple Alternatives
if (condition1)
statement1;
else if (condition2)
statement2;
else if (condition3)
statement3;
else
statement4;
The first matching condition is executed.
Order matters.

Multiple Alternatives
Order matters:
if (condition1)

Statement1;
else if (condition2)
Statement2;
else if (condition3)
Statement3;
else // option executes of all conditions fail
Statement4;

Nested Branches
Branch inside another branch
if (condition1)
{
if (condition1a)
statement1a;
else
statement1b;
}
else
statement2;

The boolean Type


George Boole (1815-1864): pioneer in the
study of logic
value of expression amount < 1000 is true or
false.
boolean type: set of 2 values, true and false

Predicate Method
return type boolean
Example:
public boolean isOverdrawn()
{ return balance < 0; }
Use in conditions
if (harrysChecking.isOverdrawn()) ...
Useful predicate methods in Character class:
isDigit
isLetter
isUpperCase
isLowerCase
if (Character.isUpperCase(ch)) ...

Boolean Operators
! not
&& and (short circuited)
|| or (short circuited)
A

!A

true

false

false

true

Truth Tables
A

A && B

true

true

true

true
false

false
Any

false
false

A
true
false
false

B
Any
true
false

A || B
true
true
false

Boolean Variables
private boolean married;
Set to truth value:
married = input.equals("M");
Use in conditions:
if (married) ... else ...
if (!married) ...
Also called flag
Don't test Boolean variables against truth values-sign of cluelessness:
if (married == true) // DON'T
if (married == false) // DON'T
if (married != false) // NO!!!

Investment with Compound


Interest
Invest $10,000, 5% interest, compounded annually

Year Balance
0
$10,000
1
$10,500
2
$11,025
3 $11,576.25
When will the balance be at least $20,000?

while Statement
while (condition)
statement;
//repeats the statement while the condition is true
while (balance < targetBalance){
year++;
double interest = balance * rate / 100;
balance = balance + interest;
}

Flowchart for while Loop

Common Error: Infinite Loop


while (year < 20)
{
balance = balance +
balance * rate / 100;
}
while (year > 0)
{
year++; // oops, meant -}
Loops run forever--must kill program

Common Error: Off-by-1


Error
year = 0;
while (balance < targetBalance){
year++;
double interest = balance * rate / 100;
balance = balance + interest;
}
System.out.println("Reached target after "
+ year + " years.");
Should year start at 0 or 1?
Should the test be < or <=?

Avoiding Off-by-1 Error


Run through a simple example:
target balance = $20,000, interest rate 50%
after one year: balance = $15,000
after two years: balance = $22,500
Therefore: year must start at 0
interest rate 100%
after one year: balance = $20,000
loop should stop
Therefore: must use <
Think, don't compile and try at random

do Statement
Executes loop body at least once:
do
statement
while (condition);
Example: Validate input
double value;
do{
String input = JOptionPane.showInputDialog(
"Please enter a positive number");
value = Integer.parseInt(input);
} while (input <= 0);

Flowchart for do Loop

for Statement
for (initialization; condition; update)
statement
Example:
for (int i = 1; i <= n; i++){
double interest = balance * rate / 100;
balance = balance + interest;
}
Equivalent to:
initialization;
while (condition){
statement;
update;
}

Flowchart for for Loop

Common Errors: Semicolons


A semicolon that shouldn't be there
sum = 0;
for (i = 1; i <= 10; i++);
sum = sum + i;
System.out.println(sum);

Common Errors: Semicolons


A semicolon that shouldn't be there

sum = 0;
i = 1;
while ( i <= 10) ;
{
sum = sum + i;
i = i + 1;
}
System.out.println(sum);

Nested Loops
Create triangle pattern
[]
[][]
[][][]
[][][][]
Loop through rows
for (int i = 1; i <= n; i++)
{
// make triangle row
}

Make triangle row is another loop


for (int j = 1; j <= i; j++)
r = r + "[]";
r = r + "\n";

Put loops together => Nested loops


for (int i = 1; i <= width; i++) {
// make triangle row
for (int j = 1; j <= i; j++)
r = r + "[]";
r = r + "\n";
}

Reading Input Values


General pattern:
boolean done = false;
while (!done)
{
String input = read input;
if (end of input indicated)
done = true;
else
{
process input
}
}
"Loop and a half"

Another option
General pattern:

while (end of input != read input ){


process input
}

String Tokenization
StringTokenizer breaks up string into tokens
By default, white space separates tokens
"4.3 7 -2" breaks into three tokens:
"4.3", "7", "-2"
StringTokenizer tokenizer
= new StringTokenizer(a String);
while (tokenizer.hasMoreTokens())
{
String token = tokenizer.nextToken();
process token
}

Traversing Characters in String


s.charAt(i) is the ith character of the string s

for (int i = 0; i < s.length(); i++)


{
char ch = s.charAt(i);
process ch
}

You might also like