Download Chapter 4 - Control Structures: Part 1

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1
Chapter 4 and 5 - Control Structures
Outline
Chapter 4
Introduction
Control Structures
if Single-Selection Statement
if else Selection Statement
while Repetition Statement
Assignment Operators
Increment and Decrement Operators
Primitive Types
Chapter 5
for Repetition Statement
Examples Using the for Statement
do…while Repetition Statement
switch Multiple-Selection Statement
break and continue Statements
Logical Operators
2
Introduction
• We learn about Control Structures
– Control structures
3
Control Structures
• Java has a sequence structure “built-in”
• Java provides three selection structures
– if
– If…else
– switch
• Java provides three repetition structures
– while
– do…while
– do
• Each of these words is a Java keyword
4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Fig. 4.7: Average1.java
// Class-average program with counter-controlled repetition.
import javax.swing.JOptionPane;
Declare variables;
gradeCounter is the counter
public class Average1 {
public
{
int
int
int
int
static void main( String args[] )
total;
gradeCounter;
grade;
average;
//
//
//
//
sum of grades input by user
number of grade to be entered next
grade value
average of grades Continue looping
String gradeString; // grade typed by
as long as
gradeCounter is less than or
user
equal to 10
// initialization phase
total = 0;
// initialize total
gradeCounter = 1;
// initialize loop counter
// processing phase
while ( gradeCounter <= 10 ) {
// loop 10 times
// prompt for input and read grade from user
gradeString = JOptionPane.showInputDialog(
"Enter integer grade: " );
// convert gradeString to int
grade = Integer.parseInt( gradeString );
Outline
Average1.java
gradeCounter
Line 21
5
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
total = total + grade;
gradeCounter = gradeCounter + 1;
// add grade to total
// increment counter
} // end while
Average1.java
// termination phase
average = total / 10;
// integer division
// display average of exam grades
JOptionPane.showMessageDialog( null, "Class average is " + average,
"Class Average", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
} // end main
} // end class Average1
Outline
// terminate the program
6
Outline
Average1.java
7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Fig. 4.9: Average2.java
// Class-average program with sentinel-controlled repetition.
import java.text.DecimalFormat; // class to format numbers
import javax.swing.JOptionPane;
public class Average2 {
public static void main( String args[] )
{
int total;
// sum of grades
int gradeCounter;
// number of grades entered
int grade;
// grade value
double average;
// number with decimal point for average
String gradeString;
// grade typed by user
// initialization phase
total = 0;
// initialize total
gradeCounter = 0; // initialize loop counter
// processing phase
// get first grade from user
gradeString = JOptionPane.showInputDialog(
"Enter Integer Grade or -1 to Quit:" );
// convert gradeString to int
grade = Integer.parseInt( gradeString );
Outline
Average2.java
8
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// loop until sentinel value read from user
while ( grade != -1 ) {
total = total + grade;
//loop
add until
gradegradeCounter
to total
gradeCounter = gradeCounter + 1; // equals
increment
counter
sentinel
value (-1)
// get next grade from user
gradeString = JOptionPane.showInputDialog(
"Enter Integer Grade or -1 to Quit:" );
// convert gradeString to int
Format numbers to
grade = Integer.parseInt( gradeString ); hundredth
Average2.java
Line 31
nearest
} // end while
// termination phase
DecimalFormat twoDigits = new DecimalFormat( "0.00" );
// if user entered at least one grade...
if ( gradeCounter != 0 ) {
// calculate average of all grades entered
average = (double) total / gradeCounter;
// display average with two digits of precision
JOptionPane.showMessageDialog( null,
"Class average is " + twoDigits.format( average ),
"Class Average", JOptionPane.INFORMATION_MESSAGE );
} // end if part of if...else
Outline
Line 45
9
60
61
62
63
64
65
66
67
68
else // if no grades entered, output appropriate message
JOptionPane.showMessageDialog( null, "No grades were entered",
"Class Average", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
} // end main
} // end class Average2
// terminate application
Outline
Average2.java
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
// Fig. 4.11: Analysis.java
// Analysis of examination results.
import javax.swing.JOptionPane;
Loop until student counter isAnalysis.java
greater than 10
Line 19
public class Analysis {
public static void main( String args[] )
{
// initializing variables in declarations
int passes = 0;
// number of passes
int failures = 0;
// number of failures
int studentCounter = 1; // student counter
int result;
// one exam result
String input;
String output;
// user-entered value
// output string
// process 10 students using counter-controlled loop
while ( studentCounter <= 10 ) {
Nested control structure
// prompt user for input and obtain value from user
input = JOptionPane.showInputDialog(
"Enter result (1 = pass, 2 = fail)" );
// convert result to int
result = Integer.parseInt( input );
// if result 1, increment passes; if...else nested in while
if ( result == 1 )
passes = passes + 1;
Line 29
11
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
else // if result not 1, increment failures
failures = failures + 1;
// increment studentCounter so loop eventually terminates
studentCounter = studentCounter + 1;
} // end while
// termination phase; prepare and display results
output = "Passed: " + passes + "\nFailed: " + failures;
// determine whether more than 8 students passed
if ( passes > 8 )
output = output + "\nRaise Tuition";
JOptionPane.showMessageDialog( null, output,
"Analysis of Examination Results",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
} // end main
} // end class Analysis
// terminate application
Outline
Analysis.java
12
Assignment Operators
• Assignment Operators
•c = c + 3
– can be written as
• c += 3
13
Assig nm ent
Sa m p le
Exp la na tion
op era tor
exp ression
Assume: int c = 3,
d = 5, e = 4, f
= 6, g = 12;
+=
c += 7
c = c + 7
-=
d -= 4
d = d - 4
*=
e *= 5
e = e * 5
/=
f /= 3
f = f / 3
%=
g %= 9
g = g % 9
Fig. 4.12 Arithm etic a ssig nm ent op era to rs.
Assig ns
10 to c
1 to d
20 to e
2 to f
3 to g
14
Increment and Decrement Operators
• Unary increment operator (++)
– Increment variable’s value by 1
• Unary decrement operator (--)
– Decrement variable’s value by 1
• Preincrement / predecrement operator
• Post-increment / post-decrement operator
15
Op era tor Ca lled
++
preincrement
++
postincrement
--
predecrement
--
postdecrement
Fig. 4.13 The inc rem ent
Sa m p le
exp ression
++a
Exp la na tion
Increment a by 1, then use the new
value of a in the expression in
which a resides.
a++
Use the current value of a in the
expression in which a resides, then
increment a by 1.
--b
Decrement b by 1, then use the
new value of b in the expression in
which b resides.
b-Use the current value of b in the
expression in which b resides, then
decrement b by 1.
a nd d ec re m ent op era tors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
5
5
6
5
6
6
16
// Fig. 4.14: Increment.java
// Preincrementing and postincrementing operators.
public class Increment {
Outline
Line 13 postincrements c
public static void main( String args[] )
{
int c;
// demonstrate postincrement
c = 5;
//
System.out.println( c );
//
System.out.println( c++ ); //
System.out.println( c );
//
System.out.println();
// skip a line
// demonstrate preincrement
c = 5;
//
System.out.println( c );
//
System.out.println( ++c ); //
System.out.println( c );
//
} // end main
} // end class Increment
assign 5 to c
print 5 Line 21 preincrements
print 5 then postincrement
print 6
assign 5 to c
print 5
preincrement then print 6
print 6
Increment.java
Line 13 postincrement
Line 21 preincrement
c
17
Primitive Types
• Primitive types
– “building blocks” for more complicated types
• Java is strongly typed
– All variables in a Java program must have a type
18
Typ e
boolean
Size in b its
char
16
byte
8
short
16
int
32
long
64
float
32
double
64
Fig. 4.16 The Ja va
Va lues
true or false
Sta nd a rd
[Note: The representation of a boolean is
specific to the Java Virtual Machine on each
computer platform.]
'\u0000' to '\uFFFF'
(ISO Unicode character set)
(0 to 65535)
–128 to +127
(–27 to 27 – 1)
–32,768 to +32,767
(–215 to 215 – 1)
–2,147,483,648 to +2,147,483,647
(–231 to 231 – 1)
–9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
(–263 to 263 – 1)
Negative range:
(IEEE 754 floating point)
–3.4028234663852886E+38 to
–1.40129846432481707e–45
Positive range:
1.40129846432481707e–45 to
3.4028234663852886E+38
Negative range:
(IEEE 754 floating point)
–1.7976931348623157E+308 to
–4.94065645841246544e–324
Positive range:
4.94065645841246544e–324 to
1.7976931348623157E+308
p rim itive typ es.
19
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Outline
// Fig. 5.1: WhileCounter.java
// Counter-controlled repetition.
import java.awt.Graphics;
WhileCounter.ja
va
import javax.swing.JApplet;
Control-variableCondition
name is counter
tests for
counter’s final value
Control-variable initial value is 1
public class WhileCounter extends JApplet {
// draw lines on applet’s background
public void paint( Graphics g )
{
super.paint( g ); // call paint method inherited from JApplet
int counter = 1;
// initialization
while ( counter <= 10 ) { // repetition condition
g.drawLine( 10, 10, 250, counter * 10 );
++counter; // increment
} // end while
} // end method paint
} // end class WhileCounter
Line 14
Line 16
Increment Line
for counter
18
20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Fig. 5.2: ForCounter.java
// Counter-controlled repetition with the for statement.
import java.awt.Graphics;
import javax.swing.JApplet;
Condition tests for
Control-variable namecounter’s
is counterfinal value
public class ForCounter extends JApplet {
Control-variable initial value is 1
applet’s background
Increment for counter
// draw lines on
public void paint( Graphics g )
{
super.paint( g ); // call paint method inherited from JApplet
// for statement header includes initialization,
// repetition condition and increment
for ( int counter = 1; counter <= 10; counter++ )
g.drawLine( 10, 10, 250, counter * 10 );
} // end method paint
} // end class ForCounter
Outline
ForCounter.java
Line 16
int counter =
1;
Line 16
counter <= 10;
Line 16
counter++;
21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Fig. 5.5: Sum.java
// Summing integers with the for statement.
import javax.swing.JOptionPane;
increment number by 2 each iteration
public class Sum {
public static void main( String args[] )
{
int total = 0; // initialize sum
// total even integers from 2 through 100
for ( int number = 2; number <= 100; number += 2 )
total += number;
// display results
JOptionPane.showMessageDialog( null, "The sum is " + total,
"Total Even Integers from 2 to 100",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
} // end main
} // end class Sum
// terminate application
Outline
Sum.java
Line 12
22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Fig. 5.6: Interest.java
// Calculating compound interest.
import java.text.NumberFormat; // class for numeric formatting
Java treats floating-points as
import java.util.Locale; // class for country-specific information
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
Outline
Interest.java
type double
NumberFormat can format
numeric values as currency Lines 13-15
public class Interest {
Display
public static void main( String args[]
) currency values with
{
dollar sign ($)
double amount;
// amount on deposit at end of each year
double principal = 1000.0; // initial amount before interest
double rate = 0.05;
// interest rate
// create NumberFormat for currency in US dollar format
NumberFormat moneyFormat =
NumberFormat.getCurrencyInstance( Locale.US );
// create JTextArea to display output
JTextArea outputTextArea = new JTextArea();
// set first line of text in outputTextArea
outputTextArea.setText( "Year\tAmount on deposit\n" );
Line 18
Line 19
23
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// calculate amount on deposit for each of ten years
for ( int year = 1; year <= 10; year++ ) {
// calculate new amount for specified year
amount = principal * Math.pow( 1.0 + rate, year );
// append one line of text to outputTextArea
outputTextArea.append( year + "\t" +
moneyFormat.format( amount ) + "\n" );
} // end for
// display results
JOptionPane.showMessageDialog( null, outputTextArea,
"Compound Interest", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
} // end main
} // end class Interest
// terminate the application
Outline
Calculate amount with for
Interest.java
statement
Lines 28-31
24
do…while Repetition Statement
• do…while structure
– Similar to while structure
– Tests loop-continuation after performing body of loop
• i.e., loop body always executes at least once
25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Fig. 5.7: DoWhileTest.java
// Using the do...while statement.
import java.awt.Graphics;
Outline
DoWhileTest.jav
a
import javax.swing.JApplet;
Oval is drawn before testing
counter’s final value
public class DoWhileTest extends JApplet {
// draw lines on applet
public void paint( Graphics g )
{
super.paint( g ); // call paint method inherited from JApplet
int counter = 1;
// initialize counter
do {
g.drawOval( 110 - counter * 10, 110 - counter * 10,
counter * 20, counter * 20 );
++counter;
} while ( counter <= 10 ); // end do...while
} // end method paint
} // end class DoWhileTest
Lines 16-20
26
switch Multiple-Selection Statement
• switch statement
– Used for multiple selections
27
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig. 5.9: SwitchTest.java
// Drawing lines, rectangles or ovals based on user input.
import java.awt.Graphics;
SwitchTest.java
import javax.swing.*;
public class SwitchTest extends JApplet {
int choice; // user's choice of which shape to draw
// initialize applet by obtaining user's choice
public void init()
{
Get user’s
String input; // user's input
input in JApplet
// obtain user's choice
input = JOptionPane.showInputDialog(
"Enter 1 to draw lines\n" +
"Enter 2 to draw rectangles\n" +
"Enter 3 to draw ovals\n" );
choice = Integer.parseInt( input );
// convert input to int
} // end method init
// draw shapes on applet's background
public void paint( Graphics g )
{
super.paint( g ); // call paint method inherited from JApplet
for ( int i = 0; i < 10; i++ ) {
Outline
// loop 10 times (0-9)
Lines 16-21:
Getting user’s input
28
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
switch ( choice ) {
// determine shape to draw
user input (choice) is
Outline
case 1: // draw a line
switch
statement
determines
controlling
expression
g.drawLine( 10, 10, 250, 10 + i * 10 );
SwitchTest.java
which case label to execute,
break; // done processing case
case 2: // draw a rectangle
g.drawRect( 10 + i * 10, 10 + i
50 + i * 10, 50 + i * 10 );
break; // done processing case
depending on controlling expression
Line 32:
controlling
* 10,
expression
case 3: // draw an oval
g.drawOval( 10 + i * 10, 10 + i * 10,
50 + i * 10, 50 + i * 10 );
break; // done processing case
Line 32:
switch statement
Line 48
default: // draw string indicating invalid value entered
g.drawString( "Invalid value entered",
10, 20 + i * 15 );
} // end switch
} // end for
} // end method paint
} // end class SwitchTest
default case for invalid entries
29
Outline
SwitchTest.java
30
Outline
SwitchTest.java
31
[true]
case a
case a action(s)
break
case b action(s)
break
case z action(s)
break
[false]
[true]
case b
[false]
.
.
.
[true]
case z
[false]
default action(s)
Fig. 5.10 switch multiple-selection statement activity diagram with break statements.
32
break and continue Statements
• break statement
– Causes immediate exit from control structure
• Used in while, for, do…while or switch statements
• continue statement
– Skips remaining statements in loop body
– Proceeds to next iteration
• Used in while, for or do…while statements
33
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Outline
// Fig. 5.11: BreakTest.java
// Terminating a loop with break.
import javax.swing.JOptionPane;
BreakTest.java
public class BreakTest {
public static void main( String args[] )
{
Loop
String output = "";
int count;
for ( count = 1; count <= 10; count++ ) {
if ( count == 5 )
break;
exit for structure (break)
Line 12
when count equals 5
10 times
Lines 14-15
// loop 10 times
// if count is 5,
// terminate loop
output += count + " ";
} // end for
output += "\nBroke out of loop at count = " + count;
JOptionPane.showMessageDialog( null, output );
System.exit( 0 );
} // end main
} // end class BreakTest
// terminate application
34
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Outline
// Fig. 5.12: ContinueTest.java
// Continuing with the next iteration of a loop.
import javax.swing.JOptionPane;
public class ContinueTest {
public static void main( String args[] )
{
String output = "";
ContinueTest.ja
Skip line 16 and proceed va
to
line 11 when count equals 5
Line 11
Loop 10 times
for ( int count = 1; count <= 10; count++ ) {
if ( count == 5 )
continue;
// loop 10 times
// if count is 5,
// skip remaining code in loop
output += count + " ";
} // end for
output += "\nUsed continue to skip printing 5";
JOptionPane.showMessageDialog( null, output );
System.exit( 0 );
// terminate application
} // end main
} // end class ContinueTest
Lines 13-14
35
Logical Operators
• Logical operators
– Allows for forming more complex conditions
– Combines simple conditions
• Java logical operators
–
–
–
–
–
–
&&
&
||
|
^
!
(conditional AND)
(boolean logical AND)
(conditional OR)
(boolean logical inclusive OR)
(boolean logical exclusive OR)
(logical NOT)