Professional Documents
Culture Documents
Week 4
By
Javed Siddique
Objectives
After this week, you should be able to
Implement a selection control using
if statements
switch statements
Understand boolean expressions
Understand nested if statements
Describe how objects are compared
Choices
Consider a program that:
repeatedly calculates monthly loan payments until we
enter $0; or
checks that you have not entered a negative value for
the LoanCalculator program; or
inputs a number and reports whether it is even (or a
perfect square, prime number etc.).
These represent choices of which statement to
execute next.
E.g. if the input is negative, print out an error,
else compute the payments as usual.
Java’s if and switch statements are used for this
purpose.
Flow of control
Once a statement is executed, the next
statement of the program is executed.
Calling a method transfers the control to
the statements in the method.
Once the method returns, control returns to
statement that made the call.
Changing this flow of control is achieved
using if and switch (and other) statements.
These are called control flow statements.
Syntax for the if Statement
if ( <Boolean expression> )
<then block>
else
<else block>
Boolean Expression
if ( testScore < 70 )
else
is
JOptionPane.showMessageDialog(null,
"You passed " ); false testScore < 70
true
?
JOptionPane. JOptionPane.
showMessageDialog showMessageDialog
(null, "You passed); (null, "You did not pass");
next statement;
Boolean expressions
boolean is a primitive data type.
A boolean expression can take only two
values: true or false
A simple boolean expression compares
two values using a relational operator, e.g.
testScore < 70
j>i
balance == 100;
Relational Operators
< //less than
<= //less than or equal to
== //equal to
!= //not equal to
> //greater than
>= //greater than or equal to
testScore < 80
testScore * 2 >= 350
30 < w / (h * h)
x + y != 2 * (a + b)
2 * Math.PI * radius <= 359.99
Compound Statements
Use braces if the <then> or <else> block has
multiple statements.
if (testScore < 70)
{
JOptionPane.showMessageDialog(null,
"You did not pass“ );
Then Block
JOptionPane.showMessageDialog(null,
“Try harder next time“ );
}
else
{
JOptionPane.showMessageDialog(null,
“You did pass“ );
Else Block
JOptionPane.showMessageDialog(null,
“Keep up the good work“ );
}
Style Guide
if ( <boolean expression> ) {
…
}
Style 1
else {
…
}
if ( <boolean expression> )
{
…
} Style 2
else
{
…
}
else is optional
if ( <boolean expression> )
<statement>
Boolean Expression
if ( testScore >= 95 )
false is
testScore >=95
true
?
JOptionPane.
showMessageDialog(null,
"You are an honor student”);
next statement;
The Nested-if Statement
The then and else block of an if statement can
contain any valid statements, including other if
statements. An if statement containing another if
statement is called a nested-if statement.
inner if
is true
false testScore >= 70
?
is
false
studentAge < 10 true
?
messageBox.show
("You did not pass");
messageBox.show messageBox.show
("You passed"); ("You did a great job");
Writing a Proper if Control
if (num1 < 0) negativeCount = 0;
if (num2 < 0)
if (num3 < 0)
negativeCount = 3; if (num1 < 0)
else negativeCount++;
negativeCount = 2;
if (num2 < 0)
else
negativeCount++;
if (num3 < 0)
negativeCount = 2; if (num3 < 0)
else negativeCount++;
negativeCount = 1;
else
if (num2 < 0)
if (num3 < 0)
negativeCount = 2;
else
negativeCount = 1; The statement
else
if (num3 < 0) negativeCount++;
negativeCount = 1;
else
increments the variable by one
negativeCount = 0;
if – else if Control
if (score >= 90)
System.out.print("Your grade is A");
if (isValid(30)) {
…
Can be used as } else {
…
}
Quiz
What is the output of the method main?
class Temp {
public static void main( String args[] ) {
T2 t;
t = new T2();
t.test(1);
}
}
class T2 {
int i;
public void T2(){
i=0;
}
public void test(int j){
int i=2;
System.out.println(“The value of i is: “ + i);
}
}
Comparing Objects
if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}
if (str1 == str2) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}
if (str1.equals(str2)) {
System.out.println("They are equal");
} else {
System.out.println("They are not equal");
}
Java Java
str1==str2 ?
false
Java
str1==str2 ?
true
In creating String objects
String word1, word2;
word1 word2
word1 = new String(“Java”);
word2 = new String(“Java”);
switch (recSection) {
This statement
is executed if
case 1: System.out.print("Go to UNIV 101”); the gradeLevel
break; is equal to 1.
case 3: x = 30;
false
} true
N ==2? x=20;
false
true
N ==3? x=30;
false
next statement;
switch with break, and default
previous statement;
switch ( N ) { true
N ==1? x=10;
case 1: x = 10;
break; false break;
true
case 2: x = 20; N ==2? x=20;
case 3: x = 30;
false
break; true
default: x = 0; N ==3? x=30;
} false break;
x=0;
next statement;
Missing case body
previous statement;
switch ( N ) { true
N ==1? x=10;
case 1: x = 10;
break; false break;
true
case 2: N ==2?
case 3: x = 30;
false
break; true
default: x = 0; N ==3? x=30;
} false break;
x=0;
next statement;
Characters
In Java, single characters are represented
using the data type char.
Character constants are written as symbols
enclosed in single quotes.
Characters are stored in memory using some
form of encoding.
ASCII, which stands for American Standard
Code for Information Interchange, is one of
the document coding schemes widely used
today.
Java uses Unicode, which includes ASCII, for
representing char constants.
ASCII Encoding
Unicode Encoding
The Unicode Worldwide Character Standard
(Unicode) supports the interchange, processing,
and display of the written texts of diverse
languages.
Java uses the Unicode standard for representing
char constants.
A UNICODE character takes up two bytes. ASCII
characters take up one byte.
char ch1 = 'X';
System.out.println(ch1); X
System.out.println( (int) ch1); 88
Character Processing
char ch1, ch2 = ‘X’; Declaration and
initialization
if( ch1 < ‘A’ && ch2 == 99) Can compare characters
with numbers directly.
System.out.print(“Done”);
Drawing Graphics
Chapter 5 introduces four standard classes
related to drawing geometric shapes. They
are
java.awt.Graphics
java.awt.Color
java.awt.Point
java.awt.Dimension
These classes are used in the Sample
Development section
Please refer to Java API for details
Sample Drawing
import javax.swing.*; //for JFrame
import java.awt.*; //for Graphics and Container
class Ch5SampleGraphics {
JFrame win;
Container contentPane;
Graphics g;
contentPane = win.getContentPane();
g = contentPane.getGraphics();
g.drawRect(50,50,100,30);
}
}
The Effect of drawRect
graphic.drawRect(<x>, <y>, <width>, <height>);
graphic.drawRect(50,50,100,30);
Position(0,0)
x
Position(50,50)
30
y 100
Objectives
After this week, you should be able to
Understand looping constructs:
while, do-while, for
Understand nested looping statements
Implement a generic loop-and-a-half repetition
control statement
Prompt the user for a yes-no reply using the
showConfirmDialog method of JOptionPane.
(Optional) Write simple recursive methods
Definition
Repetition statements control a block of code
to be executed for a fixed number of times or
until a certain condition is met.
Count-controlled repetitions terminate the
execution of the block after it is executed for
a fixed number of times.
Sentinel-controlled repetitions terminate the
execution of the block after one of the
designated conditions called a sentinel is
encountered.
Repetition statements are also called loop
statements.
The while Statement
}
Syntax for the while Statement
while ( <boolean expression> )
<statement block>
Boolean Expression
false
next statement;
More Examples
1 int sum = 0, number = 1; Keeps adding the
numbers 1, 2, 3, … until
while ( sum <= 1000000 ) { the sum becomes larger
than 1,000,000.
sum = sum + number;
number = number + 1;
}
gcd = i; int r = n % m;
} while (r != 0) {
i++; n = m;
} m = r;
return gcd; r = n % m;
} }
return m;
}
inputStr = JOptionPane.showInputDialog(null,
"Your Age (between 0 and 130):");
age = Integer.parseInt(inputStr);
inputStr = JOptionPane.showInputDialog(null,
"Your Age (between 0 and 130):");
age = Integer.parseInt(inputStr);
}
Useful Shorthand Operators
+= a += b a=a+b
-= a -= b a=a-b
*= a *= b a=a*b
/= a /= b a=a/b
%= a %= b a=a%b
Watch Out for Pitfalls
• Watch out for the off-by-one error (OBOE).
• Make sure the loop body contains a
statement that will eventually cause the loop
to terminate.
• Make sure the loop repeats exactly the
correct number of times.
• If you want to execute the loop body N times,
then initialize the counter to 0 and use the
test condition counter < N or initialize the
counter to 1 and use the test condition
counter <= N.
Loop Pitfall - 1
1 int product = 0;
Infinite Loops
Both loops will not
terminate because the
boolean expressions
2 int count = 1; will never become false.
while ( count != 10 ) {
count = count + 2;
}
Overflow
An infinite loop often results in an overflow error.
An overflow error occurs when you attempt to
assign a value larger than the maximum value
the variable can hold.
In Java, an overflow does not cause program
termination. With types float and double, a value
that represents infinity is assigned to the variable.
With type int, the value “wraps around” and
becomes a negative value.
Loop Pitfall - 2
1 float count = 0.0f;
3 count = 0; 4 count = 0;
while ( count <= 10 ){ while ( count < 10 ){
. . . . . .
count++; count++;
} }
do {
do {
Boolean Expression
Control Flow of while
previous statement;
sum += number;
number++;
true
number <= 100 ?
false
next statement;
The for Statement
int i, sum = 0, number;
number = scanner.nextInt( );
sum += number;
}
These statements are
executed 20 times
( i = 0, 1, 2, … , 19).
for statement syntax
for ( <initialization>; <boolean expression>; <increment> )
<statement>
Boolean
Initialization Increment
Expression
}
Control flow of for
previous statement;
i=0;
true
sum += number;
number++;
next statement;
i++;
More for Loop Examples
1 for (int i = 0; i < 100; i += 5)
i = 0, 5, 10, … , 95
j = 2, 4, 8, 16, 32
int price;
System.out.print(“ 5 10 15 20 25”);
for (int width = 11; width <=20; width++){
System.out.print (width + " ");
for (int length = 5; length <=25, length+=5){
INNER
int sum;
for (int i=0, sum=0; i <= 10; sum+=i, i++){
}
System.out.println(”Sum from 1 to 20 is:” + sum);
breaking out of a loop
In some cases, it is necessary to get out of a loop.
This is achieved using a break statement.
int price;
System.out.print(“ 5 10 15 20 25”);
for (int width = 11; width <=20; width++){
System.out.print (width + " ");
for (int length = 5; length <=25; length+=5){
price = width * length * 19; //$19 per sq. ft.
System.out.print (" " + price);
if(price > 3000)
break;
}
//finished one row; move on to next row
System.out.println("");
}
breaking out of outer loop
int price;
System.out.print(“ 5 10 15 20 25”);
for (int width = 11; width <=20; width++){
System.out.print (width + " ");
for (int length = 5; length <=25; length+=5){
Breaks
priceout of* innermost
= width length * 19; //$19loop
per sq.in
ft.which the
statement
}
is contained.
System.out.print (" " + price);
String name;
while (true){
if (name.length() > 0)
break;
int j=0;
String name;
for (int i=0;i<10;i++);
{
name = JOptionPane.showInputDialog(null, ”Enter int");
j += name.parseInt(name);
}
Confirmation Dialog
A confirmation dialog can be used to prompt the
user to determine whether to continue a repetition
or not.
JOptionPane.showConfirmDialog(null,
/*prompt*/ "Play Another Game?",
/*dialog title*/ "Confirmation",
/*button options*/ JOptionPane.YES_NO_OPTION);
Example: Confirmation Dialog
boolean keepPlaying = true;
int selection;
while (keepPlaying){
selection = JOptionPane.showConfirmDialog(null,
"Play Another Game?",
"Confirmation",
JOptionPane.YES_NO_OPTION);
Example:
int num1 = 34, num2 = 9;
int num3 = num1 + num2;
3 4 + 9 = 4 3
The format Method of PrintStream
Instead of using the Formatter class directly, we
can achieve the same result by using the format
method of PrintStream (System.out)
Formatter formatter = new Formatter(System.out);
formatter.format("%6d", 498);
is equivalent to
System.out.format("%6d", 498);
Control Strings
Integers
% <field width> d
Real Numbers
% <field width> . <decimal places> f
Strings
% s
long elapsedTimeInMilliSec =
endTime.getTime() – startTime.getTime();
Problem Statement
Write an application that will play Hi-Lo games
with the user. The objective of the game is for the
user to guess the computer-generated secret
number in the least number of tries. The secret
number is an integer between 1 and 100,
inclusive. When the user makes a guess, the
program replies with HI or LO depending on
whether the guess is higher or lower than the
secret number. The maximum number of tries
allowed for each game is six. The user can play
as many games as she wants.
Overall Plan
Tasks:
do {
JOptionPane
Ch6HiLo
Math
main class
standard classes
Development Steps
We will develop this program in four
steps:
Directory: Chapter6/Step1
guessCount++;
if (guess == secretNumber) {
print the winning message;
} else {
print the losing message;
}
Step 2 Code
Directory: Chapter6/Step2
Directory: Chapter6/Step3