Java i lecture_5
Upcoming SlideShare
Loading in...5
×
 

Java i lecture_5

on

  • 251 views

 

Statistics

Views

Total Views
251
Views on SlideShare
251
Embed Views
0

Actions

Likes
0
Downloads
1
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters

Java i lecture_5 Java i lecture_5 Presentation Transcript

  • Java I--Copyright © 2000 Tom Hunter
  • Java I--Copyright © 2000 Tom HunterChapter 5Control Structures: Part II
  • Java I--Copyright © 2000 Tom Hunter• Used when you know in advance how many times youwant the loop to be executed.4 Requirements:1. Variable to count the number of repetitions2. Starting value of counter3. Amount in increment the counter each loop4. The condition that decides when to stop looping.Counter-Controlled Repetition
  • Java I--Copyright © 2000 Tom Hunter• Can Use the while Loop• Although the while is usually used when we don’tknow how many times we’re going to loop, it works justfine.• Still must supply the 4 Requirements.Counter-Controlled Repetition
  • 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 valuewhile( counter <= 10 ) // 4.) condition, final value{g.drawLine( 10, 10, 250, counter * 10 );++counter; // 3.) increment}}}
  • Java I--Copyright © 2000 Tom Hunter• The for Loop• A common structure called a for loop is speciallydesigned to manage counter-controlled looping.Counter-Controlled Repetitionfor( int x = 1; x < 10; x++ )1.) count variable,2.) starting value3.) Increment4.) condition, final value
  • 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 variable2.) starting value3.) increment4.) condition, final value• When appropriate, the for is quick and easy.Counter-Controlled Repetition
  • Java I--Copyright © 2000 Tom HunterCounter-Controlled Repetition• The for loop is a do-while.• It tests the condition before itexecutes the loop for the first time.( • Note: since the variable int counter wasdeclared within the for , it vanishes after thefor is finished. )
  • Java I--Copyright © 2000 Tom Huntercounter <= 10?int counter = 1;{ }counter++TRUEFALSE1. 2.3. body4.
  • Java I--Copyright © 2000 Tom Hunter• All Three Sections are Optional• Effects of Omitting Sections: conditionCounter-Controlled Repetitionfor( int x = 1; x < 10; x++ )• If you omit the condition, Javaassumes the statement is true, andyou have an infinite loop.for( int x = 1;; x++ )
  • Java I--Copyright © 2000 Tom Hunter• Effects of Omitting Sections: initializationCounter-Controlled Repetitionfor( int x = 1; x < 10; x++ )• You can omit the initialization ifyou have initialized the controlvariable someplace else.int x = 1;for(; x < 10; x++ )
  • Java I--Copyright © 2000 Tom Hunter• Effects of Omitting Sections: incrementCounter-Controlled Repetitionfor( int x = 1; x < 10; x++ )• You can omit the increment ofthe variable if you are doing sowithin the body of the loop.for( int x = 1; x < 10;){other stuffx++;}
  • 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 InterestIntroducing two new class objects:DecimalFormatand theJTextArea.JTextArea is one of many GUI classesthat we use to put text onto a window
  • 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 InterestThis is the common style of creating objects.ObjectType instanceName.After this statement executes, twoDig is acomplete example, or instance, of theDecimalFormat class.Actually, since it hasn’t been initialized,twoDig is still only a reference.w
  • 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 InterestEvery class has a default method—a Constructor—whose onlypurpose 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
  • 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 InterestOnce again, we have the same pattern. The name of a class—JTextArea—followed by the name of an instantiationof that class—output.Next, we fire off the default Constructor using thenew keyword. In this case, we are making a JTextArea11 columns wide by 20 columns tall.
  • Java I--Copyright © 2000 Tom Hunter• A JTextArea is a multi-line area that displays plain text.• This is the actualdocumentation for theJTextArea. Youmust becomecomfortablelooking up andinterpreting thisinformation.Here, you shouldnotice that there are several Constructors.The top one—which you notice takes no arguments—isthe “default” Constructor.JTextArea—a brief sidebar
  • 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( “YeartAmount on depositn” );System.exit( 0 );} // end of main()} // end of class InterestSince output is an object of type JTextArea, it possesses all themethods of that object. Method append says to add the String data tothe JTextArea in the order that we wish it to appear within theJTextArea.Notice, we can either pass it a String object (a variable that contains aString object), or we can just pass it a String.
  • 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( “YeartAmount on depositn” );for( int year = 1; year <= 10; year++ ){} // end of forSystem.exit( 0 );} // end of main()} // end of class Interest
  • 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( “YeartAmount on depositn” );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 forSystem.exit( 0 );} // end of main()} // end of class InterestSince Java has no exponentiation operator,we calling on the Math library’s method(pow for power).Notice, it expects as arguments twodoubles. These will be used in this way:abor (1.0 + rate)yearThe return value is a double.
  • 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( “YeartAmount on depositn” );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 forJOptionPane.showMessageDialog( null, output,“Compound Interest”, JOptionPane.INFORMATION_MESSAGE);System.exit( 0 );} // end of main()} // end of class Interest
  • 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( “YeartAmount on depositn” );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 forJOptionPane.showMessageDialog( null, output,“Compound Interest”, JOptionPane.INFORMATION_MESSAGE);System.exit( 0 );} // end of main()} // end of class Interest
  • Java I--Copyright © 2000 Tom HunterCounter-Controlled Repetition
  • Java I--Copyright © 2000 Tom HunterMultiple-Selection Structure• Once you start nesting many ‘if’s, it becomes a nuisance.• Java—like C and C++ before it—provides the switchstructure, which provides multiple selections.• Unfortunately—in contrast to Visual Basic’s SelectCase and even COBOL’s Evaluate—you cannot useany of type of argument in the switch statement otherthan an integer.
  • Java I--Copyright © 2000 Tom Hunterint 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 itreaches a break;w
  • Java I--Copyright © 2000 Tom HunterMultiple-Selection Structurew• The expression within the switch( expression )section must evaluate to an integer.• Actually, the expression can evaluate to any of thesetypes (all numeric but long):byteshortintcharbut they will be reduced to an integer and that valuewill be used in the comparison.
  • Java I--Copyright © 2000 Tom HunterMultiple-Selection Structurew• The expression after each case statement can only be aconstant integral expression—or any combination of character constants and integerconstants that evaluate to a constant integer value.
  • Java I--Copyright © 2000 Tom HunterMultiple-Selection Structurew• The default: is optional.• If you omit the default choice, then it is possiblefor none of your choices to find a match and thatnothing will be executed.• If you omit the break; then the code for everychoice after that—except the default!—will beexecuted.
  • Java I--Copyright © 2000 Tom HunterMultiple-Selection Structure• Question: if only integer values can appear in theswitch( x ) statement, then how is it possible fora char to be the expression?
  • Java I--Copyright © 2000 Tom HunterStatementsbreak; 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
  • Java I--Copyright © 2000 Tom HunterStatements break; and continue;• After a break exits the “structure”—whatever thatis—execution resumes with the first statementfollowing the structure.• If you have nested structures—be they a while,do/while/ for or switch—the break will only exit theinnermost 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.
  • Java I--Copyright © 2000 Tom HunterStatements break; and continue;• The continue statement, when used in a while ordo/while or a for, skips the remaining code in thestructure and returns up to the condition.• If the condition permits it, the next iteration of theloop 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.
  • Java I--Copyright © 2000 Tom HunterStatements break; and continue;• The “Labeled” continue and break statements sendexecution 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”;}
  • Java I--Copyright © 2000 Tom HunterJScrollPane—a brief sidebar• We are all familiar with the scrollable pane—it meansthe amount of text available is larger than the screen.• Java provides the JScrollPane, which is an API that iscapable of scrolling text in this manner.
  • Java I--Copyright © 2000 Tom HunterJScrollPane—a brief sidebar• Bizarre construction, because it uses composition—where several smaller tools are combined to form a largertool.• A String object feeds into a JTextArea, which feeds intoa JScrollPane object.
  • Java I--Copyright © 2000 Tom HunterJScrollPane—a brief sidebarStringJTextArea( )JScrollPane( )JOptionPane( )JOptionPane( null, JScrollPane( JTextArea( String) ) )
  • Java I--Copyright © 2000 Tom HunterJScrollPane—a brief sidebar// ExploreJScrollPane.javaimport javax.swing.*;public class ExploreJScrollPane{public static void main( String args[] ){String output = "TestnTestnTestn";System.exit( 0 );}}
  • Java I--Copyright © 2000 Tom HunterJScrollPane—a brief sidebar// ExploreJScrollPane.javaimport javax.swing.*;public class ExploreJScrollPane{public static void main( String args[] ){String output = "TestnTestnTestn";JTextArea outputArea = new JTextArea( 10, 10 );outputArea.setText( output );System.exit( 0 );}}
  • Java I--Copyright © 2000 Tom HunterJScrollPane—a brief sidebar// ExploreJScrollPane.javaimport javax.swing.*;public class ExploreJScrollPane{public static void main( String args[] ){String output = "TestnTestnTestn";JTextArea outputArea = new JTextArea( 10, 10 );outputArea.setText( output );JScrollPane scroller = new JScrollPane( outputArea );System.exit( 0 );}}
  • Java I--Copyright © 2000 Tom HunterJScrollPane—a brief sidebar// ExploreJScrollPane.javaimport javax.swing.*;public class ExploreJScrollPane{public static void main( String args[] ){String output = "TestnTestnTestn";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 );}}
  • Java I--Copyright © 2000 Tom HunterJScrollPane—a brief sidebar
  • Java I--Copyright © 2000 Tom HunterLogical Operators• So far, all of the conditions we have tested were simple.• It is possible to construct complex conditions using theJava Logical Operators, which—again—were inheritedform C/C++.&& Logical AND|| Logical OR! Logical NOT
  • Java I--Copyright © 2000 Tom HunterLogical 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 2ndhalf of the expression—if the first half is false.
  • Java I--Copyright © 2000 Tom HunterLogical Operators• Logical OR—two “pipes” together. (Shift of keyunderneath backspace.)|| (no space between)if( gender == ‘F’ || age >= 65 )• Entire condition is true if either half is true.
  • Java I--Copyright © 2000 Tom HunterLogical Operators• Logical NOT—single exclamation mark.!if( !(age <= 65) )• Negates the expression—not many opportunities touse.
  • Java I--Copyright © 2000 Tom HunterLogical 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 checkboth halves of the equation, even if the first is false.
  • Java I--Copyright © 2000 Tom HunterLogical Operators• Logical inclusive Boolean OR—one pipe.|if( gender == ‘F’ | age >= 65 )• Again, this works just like the Logical OR, but youare guaranteed that both sides of the expression willalways be executed.• If either half is true, the entire ‘if’ is true.
  • Java I--Copyright © 2000 Tom HunterLogical Operators• Logical exclusive Boolean OR.^ ( shift 6 )if( gender == ‘F’ ^ age >= 65 )• This Logical exclusive Boolean OR is true only ifone side is true and the other false.• If both sides are true, the entire expression is false.