java i lecture_5

48
Java I--Copyright © 2000 Tom Hunter

Upload: mithun-dp

Post on 26-May-2015

126 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Page 2: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Chapter 5

Control Structures: Part II

Page 3: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

• Used when you know in advance how many times you want the loop to be executed.

4 Requirements:

1. Variable to count the number of repetitions

2. Starting value of counter

3. Amount in increment the counter each loop

4. The condition that decides when to stop looping.

Counter-Controlled Repetition

Page 4: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

• Can Use the while Loop

• Although the while is usually used when we don’t know how many times we’re going to loop, it works just fine.

• Still must supply the 4 Requirements.

Counter-Controlled Repetition

Page 5: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Counter-Controlled Repetition// WhileCounter.javaimport java.awt.Graphics;import javax.swing.JApplet;

public class WhileCounter extends JApplet{ public void paint( Graphics g ) {

int counter; // 1.) count variablecounter = 1; // 2.) starting value

while( counter <= 10 ) // 4.) condition, final value{

g.drawLine( 10, 10, 250, counter * 10 ); ++counter; // 3.) increment

} }}

Page 6: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

• The for Loop

• A common structure called a for loop is specially designed to manage counter-controlled looping.

Counter-Controlled Repetition

for( int x = 1; x < 10; x++ )

1.) count variable,2.) starting value

3.) Increment

4.) condition, final value

Page 7: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

// ForCounter.javaimport java.awt.Graphics;import javax.swing.JApplet;

public class ForCounter extends JApplet{ public void paint( Graphics g ) { 1. 2. 4. 3.

for( int counter=1 ; counter <= 10 ; counter++ ){

g.drawLine( 10, 10, 250, counter * 10 ); }

}} 1.) count variable 2.) starting value 3.) increment 4.) condition, final value

• When appropriate, the for is quick and easy.

Counter-Controlled Repetition

Page 8: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Counter-Controlled Repetition

• The for loop is a do-while.

• It tests the condition before it executes the loop for the first time.

( • Note: since the variable int counter was declared within the for , it vanishes after the for is finished. )

Page 9: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

counter <= 10?

int counter = 1;

{ }

counter++

TRUE

FALSE

1. 2.

3. body

4.

Page 10: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

• All Three Sections are Optional

• Effects of Omitting Sections: condition

Counter-Controlled Repetition

for( int x = 1; x < 10; x++ )

• If you omit the condition, Java assumes the statement is true, and you have an infinite loop.

for( int x = 1;; x++ )

Page 11: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

• Effects of Omitting Sections: initialization

Counter-Controlled Repetition

for( int x = 1; x < 10; x++ )

• You can omit the initialization if you have initialized the control variable someplace else.

int x = 1; for(; x < 10; x++ )

Page 12: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

• Effects of Omitting Sections: increment

Counter-Controlled Repetition

for( int x = 1; x < 10; x++ )

• You can omit the increment of the variable if you are doing so within the body of the loop.

for( int x = 1; x < 10;){

other stuff

x++;}

Page 13: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

// Calculate Compound Interestimport javax.swing.JOptionPane;import java.text.DecimalFormat;import javax.swing.JTextArea;

public class Interest{

} // end of class Interest

Introducing two new class objects:DecimalFormat

and theJTextArea.

JTextArea is one of many GUI classes that we use to put text onto a window

Page 14: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

// Calculate Compound Interestimport javax.swing.JOptionPane;import java.text.DecimalFormat;import javax.swing.JTextArea;

public class Interest{ public static void main( String args[] ) {

double amount, principle = 1000.0, rate = 0.05; DecimalFormat twoDig =

System.exit( 0 ); } // end of main()} // end of class Interest

This is the common style of creating objects.ObjectType instanceName.

After this statement executes, twoDig is a complete example, or instance, of the

DecimalFormat class.Actually, since it hasn’t been initialized,

twoDig is still only a reference.

w

Page 15: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

// Calculate Compound Interestimport javax.swing.JOptionPane;import java.text.DecimalFormat;import javax.swing.JTextArea;

public class Interest{ public static void main( String args[] ) {

double amount, principle = 1000.0, rate = 0.05; DecimalFormat twoDig = new DecimalFormat( “0.00” );

System.exit( 0 ); } // end of main()} // end of class Interest

Every class has a default method—a Constructor—whose only purpose is to initialize a fresh instantiation of the class.The new keyword fires the default “Constructor” method. The Constructor always has the exact same name as the class. ( Chapter 6 covers this in greater detail.)

w

Page 16: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

// Calculate Compound Interestimport javax.swing.JOptionPane;import java.text.DecimalFormat;import javax.swing.JTextArea;

public class Interest{ public static void main( String args[] ) {

double amount, principle = 1000.0, rate = 0.05; DecimalFormat twoDig = new DecimalFormat( “0.00” ); JTextArea output = new JTextArea( 11, 20 );

System.exit( 0 ); } // end of main()} // end of class Interest

Once again, we have the same pattern. The name of a class—JTextArea—followed by the name of an instantiation of that class—output.Next, we fire off the default Constructor using the new keyword. In this case, we are making a JTextArea 11 columns wide by 20 columns tall.

Page 17: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

• A JTextArea is a multi-line area that displays plain text.• This is the actualdocumentation for theJTextArea. You must become comfortablelooking up andinterpreting thisinformation.Here, you should notice that there are several Constructors.The top one—which you notice takes no arguments—is the “default” Constructor.

JTextArea—a brief sidebar

Page 18: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

// Calculate Compound Interestimport javax.swing.JOptionPane;import java.text.DecimalFormat;import javax.swing.JTextArea;

public class Interest{ public static void main( String args[] ) {

double amount, principle = 1000.0, rate = 0.05; DecimalFormat twoDig = new DecimalFormat( “0.00” ); JTextArea output = new JTextArea( 11, 20 );

output.append( “Year\tAmount on deposit\n” );

System.exit( 0 ); } // end of main()} // end of class Interest

Since output is an object of type JTextArea, it possesses all the methods of that object. Method append says to add the String data to

the JTextArea in the order that we wish it to appear within the JTextArea.

Notice, we can either pass it a String object (a variable that contains a String object), or we can just pass it a String.

Page 19: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

// Calculate Compound Interestimport javax.swing.JOptionPane;import java.text.DecimalFormat;import javax.swing.JTextArea;

public class Interest{ public static void main( String args[] ) {

double amount, principle = 1000.0, rate = 0.05; DecimalFormat twoDig = new DecimalFormat( “0.00” ); JTextArea output = new JTextArea( 11, 20 );

output.append( “Year\tAmount on deposit\n” ); for( int year = 1; year <= 10; year++ ) { } // end of for

System.exit( 0 ); } // end of main()} // end of class Interest

Page 20: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

// Calculate Compound Interestimport javax.swing.JOptionPane;import java.text.DecimalFormat;import javax.swing.JTextArea;

public class Interest{ public static void main( String args[] ) {

double amount, principle = 1000.0, rate = 0.05; DecimalFormat twoDig = new DecimalFormat( “0.00” ); JTextArea output = new JTextArea( 11, 20 );

output.append( “Year\tAmount on deposit\n” ); for( int year = 1; year <= 10; year++ ) { amount = principle * Math.pow( 1.0 + rate, year ); output.append( year + “\t” + twoDig.format(amount) + “\n”); } // end of for

System.exit( 0 ); } // end of main()} // end of class Interest

Since Java has no exponentiation operator, we calling on the Math library’s method

(pow for power).Notice, it expects as arguments two

doubles. These will be used in this way:

ab or (1.0 + rate)year

The return value is a double.

Page 21: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

// Calculate Compound Interestimport javax.swing.JOptionPane;import java.text.DecimalFormat;import javax.swing.JTextArea;

public class Interest{ public static void main( String args[] ) {

double amount, principle = 1000.0, rate = 0.05; DecimalFormat twoDig = new DecimalFormat( “0.00” ); JTextArea output = new JTextArea( 11, 20 );

output.append( “Year\tAmount on deposit\n” ); for( int year = 1; year <= 10; year++ ) { amount = principle * Math.pow( 1.0 + rate, year ); output.append( year + “\t” + twoDig.format(amount) + “\n”); } // end of for

JOptionPane.showMessageDialog( null, output, “Compound Interest”, JOptionPane.INFORMATION_MESSAGE);

System.exit( 0 ); } // end of main()} // end of class Interest

Page 22: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

// Calculate Compound Interestimport javax.swing.JOptionPane;import java.text.DecimalFormat;import javax.swing.JTextArea;

public class Interest{ public static void main( String args[] ) {

double amount, principle = 1000.0, rate = 0.05; DecimalFormat twoDig = new DecimalFormat( “0.00” ); JTextArea output = new JTextArea( 11, 20 );

output.append( “Year\tAmount on deposit\n” ); for( int year = 1; year <= 10; year++ ) { amount = principle * Math.pow( 1.0 + rate, year ); output.append( year + “\t” + twoDig.format(amount) + “\n”); } // end of for

JOptionPane.showMessageDialog( null, output, “Compound Interest”, JOptionPane.INFORMATION_MESSAGE);

System.exit( 0 ); } // end of main()} // end of class Interest

Page 23: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Counter-Controlled Repetition

Page 24: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Multiple-Selection Structure• Once you start nesting many ‘if’s, it becomes a nuisance.

• Java—like C and C++ before it—provides the switch structure, which provides multiple selections.

• Unfortunately—in contrast to Visual Basic’s Select Case and even COBOL’s Evaluate—you cannot use any of type of argument in the switch statement other than an integer.

Page 25: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

int x = 0;switch( x )

{case 1:

do stuff;break;

case 2:do stuff;break;

case 55:do stuff;break;

case 102:case 299:

do stuff okay for both;break;

default:if nothing else do this stuff;break;

}

Multiple-Selection Structure

• The integer expression x isevaluated. If x contains a 1,then the case 1 branch isperformed. Notice the‘break;’ statement. This is required. Without it,every line after the matchwill be executed until it

reaches a break;

w

Page 26: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Multiple-Selection Structure

w

• The expression within the switch( expression )section must evaluate to an integer.• Actually, the expression can evaluate to any of these types (all numeric but long):

byteshortint char

but they will be reduced to an integer and that value will be used in the comparison.

Page 27: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Multiple-Selection Structure

w

• The expression after each case statement can only be a

constant integral expression

—or any combination of character constants and integer constants that evaluate to a constant integer value.

Page 28: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Multiple-Selection Structure

w

• The default: is optional.• If you omit the default choice, then it is possible for none of your choices to find a match and that nothing will be executed.

• If you omit the break; then the code for every choice after that—except the default!—will be executed.

Page 29: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Multiple-Selection Structure

• Question: if only integer values can appear in the switch( x ) statement, then how is it possible for a char to be the expression?

Page 30: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Statements break; and continue;

• Both of these statements alter the flow of control.

• The break statement can be executed in a:

whiledo/whileforswitch

• break causes the immediate exit from the structure

Page 31: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Statements break; and continue; • After a break exits the “structure”—whatever that is—execution resumes with the first statement following the structure.

• If you have nested structures—be they a while, do/while/ for or switch—the break will only exit the innermost nesting.

• break will not exit you out of all nests. To do that, you need another break*

* There is a variant of the break called a labeled break—but this is similar to a goto and is frowned upon.

Page 32: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Statements break; and continue;

• The continue statement, when used in a while or do/while or a for, skips the remaining code in the structure and returns up to the condition.

• If the condition permits it, the next iteration of the loop is permitted to continue.

• So, the continue is a “temporary break.”

• The continue is only used in iterative structures, such as the while, do/while and for.

Page 33: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Statements break; and continue;

• The “Labeled” continue and break statements send execution to the label to continue execution.• Note: using the labeled break and continue is bad code. Avoid using them!

stop:

for(row = 1; row <= 10; row++){ for(col=1; col <=5; col++) { if( row == 5) {

break stop; // jump to stop block }

output += “* “; } output += “\n”;}

Page 34: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

JScrollPane—a brief sidebar

• We are all familiar with the scrollable pane—it means the amount of text available is larger than the screen.

• Java provides the JScrollPane, which is an API that is capable of scrolling text in this manner.

Page 35: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

JScrollPane—a brief sidebar • Bizarre construction, because it uses composition—where several smaller tools are combined to form a larger tool.

• A String object feeds into a JTextArea, which feeds into a JScrollPane object.

Page 36: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

JScrollPane—a brief sidebar String

JTextArea( )

JScrollPane( )

JOptionPane( )

JOptionPane( null, JScrollPane( JTextArea( String) ) )

Page 37: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

JScrollPane—a brief sidebar // ExploreJScrollPane.javaimport javax.swing.*;

public class ExploreJScrollPane{

public static void main( String args[] ){

String output = "Test\nTest\nTest\n";

System.exit( 0 );}

}

Page 38: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

JScrollPane—a brief sidebar // ExploreJScrollPane.javaimport javax.swing.*;

public class ExploreJScrollPane{

public static void main( String args[] ){

String output = "Test\nTest\nTest\n";JTextArea outputArea = new JTextArea( 10, 10 );outputArea.setText( output );

System.exit( 0 );}

}

Page 39: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

JScrollPane—a brief sidebar // ExploreJScrollPane.javaimport javax.swing.*;

public class ExploreJScrollPane{

public static void main( String args[] ){

String output = "Test\nTest\nTest\n";JTextArea outputArea = new JTextArea( 10, 10 );outputArea.setText( output );JScrollPane scroller = new JScrollPane( outputArea );

System.exit( 0 );}

}

Page 40: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

JScrollPane—a brief sidebar // ExploreJScrollPane.javaimport javax.swing.*;

public class ExploreJScrollPane{

public static void main( String args[] ){

String output = "Test\nTest\nTest\n";JTextArea outputArea = new JTextArea( 10, 10 );outputArea.setText( output );JScrollPane scroller = new JScrollPane( outputArea );

JOptionPane.showMessageDialog( null, scroller, "Test JScrollPane",JOptionPane.INFORMATION_MESSAGE );

System.exit( 0 );}

}

Page 41: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

JScrollPane—a brief sidebar

Page 42: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Logical Operators• So far, all of the conditions we have tested were simple.• It is possible to construct complex conditions using the Java Logical Operators, which—again—were inherited form C/C++.

&& Logical AND

|| Logical OR

! Logical NOT

Page 43: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Logical Operators• Logical AND—two ampersands together.

&&

if( gender == ‘F’ && age >= 65 )

• Condition is true only if both halves are true.• Java will short-circuit the process—skipping the 2nd half of the expression—if the first half is false.

Page 44: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Logical Operators• Logical OR—two “pipes” together. (Shift of key underneath backspace.)

|| (no space between)

if( gender == ‘F’ || age >= 65 )

• Entire condition is true if either half is true.

Page 45: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Logical Operators• Logical NOT—single exclamation mark.

!

if( !(age <= 65) )

• Negates the expression—not many opportunities to use.

Page 46: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Logical Operators• Logical Boolean AND—one ampersand.

&

if( gender == ‘F’ & ++age >= 65 )

• A Logical Boolean AND [ & ] works exactly likea Logical AND [ && ] with one exception.

• A Logical Boolean AND [ & ] will always check both halves of the equation, even if the first is false.

Page 47: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Logical Operators• Logical inclusive Boolean OR—one pipe.

|

if( gender == ‘F’ | age >= 65 )

• Again, this works just like the Logical OR, but you are guaranteed that both sides of the expression will always be executed.• If either half is true, the entire ‘if’ is true.

Page 48: Java i lecture_5

Java I--Copyright © 2000 Tom Hunter

Logical Operators• Logical exclusive Boolean OR.

^ ( shift 6 )

if( gender == ‘F’ ^ age >= 65 )

• This Logical exclusive Boolean OR is true only if one side is true and the other false. • If both sides are true, the entire expression is false.