1 1. 1 2 Chapter 5 Control Structures: Part II 1 3 Used when you know in advance how many times you want the loop to be executed. 4 Requirements: 1.

Slides:



Advertisements
Similar presentations
Session 5 JavaScript/JScript: Control Structures II Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
Advertisements

1 Outline Chapter 4 Introduction Control Structures if Single-Selection Statement if else Selection Statement while Repetition Statement Assignment Operators.
INSTRUCTOR: SHIH-SHINH HUANG Windows Programming Using Java Chapter5: Control Statements Part II.
Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition 5.3The for Repetition Structure 5.4Examples.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
The switch Statement, DecimalFormat, and Introduction to Looping
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 4.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled Repetition.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Jaeki Song ISQS6337 JAVA Lecture 04 Control Structure - Selection, and Repetition -
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II UTPA – Fall
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Typecasting.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
10/5: Primitives, the for loop Primitive data types –why we mention them Return to counter-controlled repetition.
University of Palestine software engineering department Introduction to data structures Control Statements: Part 1 instructor: Tasneem Darwish.
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 05 (Part III) Control Statements: Part II.
CSCI 3328 Object Oriented Programming in C# Chapter 5: C# Control Statement – Part II – Exercises 1 Xiang Lian The University of Texas Rio Grande Valley.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled.
Chapter 4 Control Structures: Part I 1 3 “ There is No goto in Java ” Structured programming: the building blocks There are 3 different kinds.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
Sections 5.1 – 5.4 © Copyright by Pearson Education, Inc. All Rights Reserved.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled Repetition.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
10/4: the for loop & the switch structure Primitive data types –why we mention them Return to counter-controlled repetition.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction principles BZUPAGES.COM.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - JavaScript: Control Structures II Outline 9.1 Introduction 9.2 Essentials of Counter-Controlled.
Java I--Copyright © Tom Hunter. Chapter 4 Control Structures: Part I.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Control Statements: Part 2
Java Programming: Guided Learning with Early Objects
MSIS 655 Advanced Business Applications Programming
Java I.
Chapter 8 JavaScript: Control Statements, Part 2
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Chapter 6 Control Statements: Part 2
Chapter 5 – Control Structures: Part 2
CSC215 Lecture Control Flow.
Chapter 5 – Control Structures: Part 2
Presentation transcript:

1 1

1 2 Chapter 5 Control Structures: Part II

1 3 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

1 4 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

1 5 Counter-Controlled Repetition // WhileCounter.java import java.awt.Graphics; import javax.swing.JApplet; public class WhileCounter extends JApplet { public void paint( Graphics g ) { int counter;// 1.) count variable counter = 1;// 2.) starting value while( counter <= 10 )// 4.) condition, final value { g.drawLine( 10, 10, 250, counter * 10 ); ++counter;// 3.) increment }

1 6 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

1 7 // ForCounter.java import java.awt.Graphics; import javax.swing.JApplet; public class ForCounter extends JApplet { public void paint( Graphics g ) { 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

1 8 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. )

1 9 counter <= 10 ? int counter = 1; { } counter++ TRUE FALSE body 4.

1 10 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++ )

1 11 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++ )

1 12 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++; }

1 13 // Calculate Compound Interest import 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 the JTextArea. JTextArea is one of many GUI classes that we use to put text onto a window

1 14 // Calculate Compound Interest import javax.swing.JOptionPane; import java.text.DecimalFormat; import javax.swing.JTextArea; public class Interest { public static void main( String args[] ) { double amount, principle = , 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

1 15 // Calculate Compound Interest import javax.swing.JOptionPane; import java.text.DecimalFormat; import javax.swing.JTextArea; public class Interest { public static void main( String args[] ) { double amount, principle = , 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

1 16 // Calculate Compound Interest import javax.swing.JOptionPane; import java.text.DecimalFormat; import javax.swing.JTextArea; public class Interest { public static void main( String args[] ) { double amount, principle = , 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.

1 17 A JTextArea is a multi-line area that displays plain text. This is the actual documentation for the JTextArea. You must become comfortable looking up and interpreting this information. 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

1 18 // Calculate Compound Interest import javax.swing.JOptionPane; import java.text.DecimalFormat; import javax.swing.JTextArea; public class Interest { public static void main( String args[] ) { double amount, principle = , 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.

1 19 // Calculate Compound Interest import javax.swing.JOptionPane; import java.text.DecimalFormat; import javax.swing.JTextArea; public class Interest { public static void main( String args[] ) { double amount, principle = , 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

1 20 // Calculate Compound Interest import javax.swing.JOptionPane; import java.text.DecimalFormat; import javax.swing.JTextArea; public class Interest { public static void main( String args[] ) { double amount, principle = , 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( 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: a b or (1.0 + rate) year The return value is a double.

1 21 // Calculate Compound Interest import javax.swing.JOptionPane; import java.text.DecimalFormat; import javax.swing.JTextArea; public class Interest { public static void main( String args[] ) { double amount, principle = , 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( 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

1 22 // Calculate Compound Interest import javax.swing.JOptionPane; import java.text.DecimalFormat; import javax.swing.JTextArea; public class Interest { public static void main( String args[] ) { double amount, principle = , 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( 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

1 23 Counter-Controlled Repetition

1 24 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.

1 25 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 is evaluated. If x contains a 1, then the case 1 branch is performed. Notice the ‘ break; ’ statement. This is required. Without it, every line after the match will be executed until it reaches a break; w

1 26 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 ) : byte short int char but they will be reduced to an integer and that value will be used in the comparison.

1 27 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.

1 28 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.

1 29 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?

1 30 Statements break; and continue; Both of these statements alter the flow of control. The break statement can be executed in a: while do/while for switch break causes the immediate exit from the structure

1 31 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.

1 32 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.

1 33 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”; }

1 34 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.

1 35 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.

1 36 JScrollPane—a brief sidebar String JTextArea( ) JScrollPane( ) JOptionPane() JOptionPane( null, JScrollPane( JTextArea( String) ) )

1 37 JScrollPane—a brief sidebar // ExploreJScrollPane.java import javax.swing.*; public class ExploreJScrollPane { public static void main( String args[] ) { String output = "Test\nTest\nTest\n"; System.exit( 0 ); }

1 38 JScrollPane—a brief sidebar // ExploreJScrollPane.java import 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 ); }

1 39 JScrollPane—a brief sidebar // ExploreJScrollPane.java import 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 ); }

1 40 JScrollPane—a brief sidebar // ExploreJScrollPane.java import 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 ); }

1 41 JScrollPane—a brief sidebar

1 42 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

1 43 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.

1 44 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.

1 45 Logical Operators Logical NOT—single exclamation mark. ! if( !(age <= 65) ) Negates the expression—not many opportunities to use.

1 46 Logical Operators Logical Boolean AND—one ampersand. & if( gender == ‘F’ & ++age >= 65 ) A Logical Boolean AND [ & ] works exactly like a Logical AND [ && ] with one exception. A Logical Boolean AND [ & ] will always check both halves of the equation, even if the first is false.

1 47 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.

1 48 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.