1 Repetition structures [cont’d] Overview l Nested Loops l Sentinel-Controlled loop l Avoiding Number Format exception.

Slides:



Advertisements
Similar presentations
Continuation of chapter 6…. Nested while loop A while loop used within another while loop is called nested while loop. Q. An illustration to generate.
Advertisements

Algorithms and Problem Solving
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 6: Iteration 1 Chapter 6 Iteration.
Repetition Chapter 4: Control structures. Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 2 Loop Statements After reading and studying this Section,
1 More on Decisions Overview l The selection Operator l Grouping of Statements l Multiple branches (if else if) l Switch Statement.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
1 Repetition structures Overview while statement for statement do while statement.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
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.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
1 More on 1-D Arrays Overview l Array as a return type to methods l Array of Objects.
String Tokenization What is String Tokenization?
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
1 Methods Overview l Closer Look at Methods l Parameter passing l Passing parameters by value l Passing parameters by reference.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
1 StringTokenizer and StringBuffer classes Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples l StringBuffer class.
Looping Yong Choi School of Business CSU, Bakersfield.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Unit 171 Algorithms and Problem Solving - II Algorithm Efficiency Primality Testing Improved Primality Testing Sieve of Eratosthenes Primality Testing.
1 Methods Overview l Closer Look at Methods l Parameter passing l Passing parameters by value l Passing parameters by reference.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
1 Repetition structures Overview while statement for statement do while statement.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Repetition Statements.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
Chapter 4: Control Structures II
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
1 Course Lectures Available on line:
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 5 Loops.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
Lec 4: while loop and do-while loop. Review from last week if Statements if (num < 0.5){...println("heads"); } if –else Statements if (num < 0.5){...println("heads");
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
9/20: The while Repetition Structure last time’s program repetition structures: what they are the while repetition structure homework due on Thursday program.
1 StringTokenization Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples.
Chapter 4: Control Structures II
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Repetition Statements while and do while loops
Chapter 5: Control Structures II
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
Iteration Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
REPETITION MTS3033 OBJECT ORIENTED PROGRAMMING 1.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Lesson 7 Iteration Structures. Iteration is the third control structure we will explore. Iteration simply means to do something repeatedly. All iteration.
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
Chapter 4 Repetition Statements (loops)
CS1101: Programming Methodology Recitation 7 – Exceptions
Chapter 5: Control Structures II
Computer Programming Methodology Input and While Loop
Repetition-Sentinel,Flag Loop/Do_While
Repetition.
Decision statements. - They can use logic to arrive at desired results
Java I.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Repetition Statements
Presentation transcript:

1 Repetition structures [cont’d] Overview l Nested Loops l Sentinel-Controlled loop l Avoiding Number Format exception

2 Nested Loops l One of the statements inside a loop (for, while or do-while) could be another while loop statement – such situation is called Nested Loops. l The following example prints the indices of a 3x3 matrix: public class NestedWhileLoop { public static void main(String[] args) { int i=1,j; while(i<=3) { j=1; while(j<=3) { System.out.print(i+","+j+"\t"); j++; } System.out.println(); i++; }

3 Nested Loops (cont’d) l The following example is a for-loop version of the previous example: public class NestedForLoop { public static void main(String[] args) { int i,j; for (i=1; i<=3; i++) { for (j=1; j<=3; j++) System.out.print(i+","+j+"\t"); System.out.println(); }

4 Nested Loops (cont’d) l The following example prints a table of x y for x from 1 to 10 and y from 1 to 5: public class Table { public static void main(String[] args) { final int COLUMN_WIDTH = 7; for (int x = 1; x <= 10; x++) { for (int y = 1; y <= 5; y++) { int p = (int)Math.pow(x, y); // convert value to string String pstr = "" + p; // pad with spaces while (pstr.length() < COLUMN_WIDTH) pstr = " " + pstr; System.out.print(pstr); } System.out.println(); }

5 Nested Loops (cont’d)

6 Sentinel-Controlled Loops l It is a common practice to write loops that repeat until a particular data value is read. Such data value is called Sentinel and the loop is called sentinel-controlled loop. l A problem usually encountered in writing such loop is how to choose the sentinel – What if the sentinel is part of the data? l The following example shows how this may be solved – by choosing the sentinel to be of type character. import java.io.BufferedReader; import java.io.InputStreamReader; public class SentinelLoop { public static void main(String[] args) throws java.io.IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter data (Q to finish):");

7 Sentinel-Controlled Loops (cont’d) double sum = 0; int count = 0; boolean done = false; while (!done) { String inputLine = stdin.readLine(); if (inputLine.equalsIgnoreCase("Q")) done = true; else { double x = Double.parseDouble(inputLine); sum = sum + x; count++; } if (count == 0) System.out.println("No data"); else System.out.println("Average = " + sum/count); }

8 Avoiding Number Format Exception l If a string that contains non-numeric characters is passed to the methods Integer.parseInt, Double.ParseDouble, etc, they throw NumberFormatException. l This can be solved by enclosing a try-and-catch statement inside a loop. import java.io.BufferedReader; import java.io.InputStreamReader; public class NumberFormat { public static void main(String[] args) throws java.io.IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); boolean inputOk = false; do { try { String inputLine = stdin.readLine(); int n = Integer.parseInt(inputLine.trim()); inputOk = true; } catch(NumberFormatException e) { System.out.println("Input Error. Try again."); } } while (!inputOk); }