1 Fencepost loops suggested reading:4.1. 2 The fencepost problem Problem: Write a static method named printNumbers that prints each number from 1 to a.

Slides:



Advertisements
Similar presentations
1 Value vs. reference semantics. Recall: Value semantics value semantics: Behavior where variables are copied when assigned to each other or passed as.
Advertisements

Building Java Programs
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-2: Strings reading: 3.3, self-check: Ch. 4 #12, 15 exercises:
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution.
Copyright 2006 by Pearson Education 1 reading: 4.1 Cumulative sum.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Introduction to Computers and Programming Strings Professor: Evan Korth New York University.
1 Text Processing. 2 Type char char : A primitive type representing single characters. –A String is stored internally as an array of char String s = "Ali.
1 Text processing. 2 text processing: Examining, editing, formatting text.  Text processing often involves for loops that examine the characters of a.
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.
1 Fencepost loops “How do you build a fence?”. 2 The fencepost problem Problem: Write a class named PrintNumbers that reads in an integer called max and.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 5/27/20161.
1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops; Procedural Design reading: 5.1 – 5.2; 4.5.
Topic 14 while loops and loop patterns Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Introduction to Programming
Building java programs, chapter 5 Program logic and indefinite loops.
1 Text processing Readings: Characters char : A primitive type representing single characters. Individual characters inside a String are stored.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 7: Arrays.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays for Tallying; Text Processing reading: 7.1, 4.4 self-checks: #1-9.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
Building Java Programs Program Logic and Indefinite Loops.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
Topic 23 arrays - part 3 (tallying, text processing) Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
CHAPTER 6 GC Strings. THE CLASS STRING  Contains operations to manipulate strings.  String:  Sequence of zero or more characters.  Enclosed.
1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 5.1 – 5.2.
Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-3: Strings, char reading: 3.3, 4.3.
1 Building Java Programs Chapter 4: Conditional Execution These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted,
Building Java Programs
CSc 110, Autumn 2017 Lecture 15: Strings and Fencepost Loops
Building Java Programs
CSc 110, Autumn 2017 Lecture 16: Fencepost Loops and Review
Building Java Programs Chapter 4
Building Java Programs
Building Java Programs
Chapter 6 GC 101 Strings.
Conditional Execution
Building Java Programs Chapter 4.3
Strings string: An object storing a sequence of text characters.
Type Conversion, Constants, and the String Object
Topic 9 Using Objects, Interactive Programs and Loop Techniques
CSc 110, Autumn 2016 Lecture 12: while Loops, Fencepost Loops, and Sentinel Loops Adapted from slides by Marty Stepp and Stuart Reges.
CSc 110, Spring 2017 Lecture 11: while Loops, Fencepost Loops, and Sentinel Loops Adapted from slides by Marty Stepp and Stuart Reges.
Building Java Programs
Fencepost loops reading: 4.1.
Building Java Programs
CSc 110, Spring 2018 Lecture 16: Fencepost Loops and while loops
Topic 14 while loops and loop patterns
Topic 23 arrays - part 3 (tallying, text processing)
Building Java Programs
Building Java Programs
Building Java Programs
Using Objects (continued)
Loop problem Write a method printLetters that prints each letter from a word separated by commas. For example, the call: printLetters("Atmosphere") should.
Building Java Programs
Suggested self-checks: Section 7.11 #1-11
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Strings string: An object storing a sequence of text characters.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
CSE 142, Spring 2013 Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 5.1 – 5.2.
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

1 Fencepost loops suggested reading:4.1

2 The fencepost problem Problem: Write a static method named printNumbers that prints each number from 1 to a given maximum, separated by commas. For example, the method call: printNumbers(5) should print: 1, 2, 3, 4, 5 Let's write a solution to this problem...

3 Flawed solutions public static void printNumbers(int max) { for (int i = 1; i <= max; i++) { System.out.print(i + ", "); } System.out.println(); // to end the line of output } OUTPUT from printNumbers(5) : 1, 2, 3, 4, 5, public static void printNumbers(int max) { for (int i = 1; i <= max; i++) { System.out.print(", " + i); } System.out.println(); // to end the line of output } OUTPUT from printNumbers(5) :, 1, 2, 3, 4, 5

4 Fence post analogy We print n numbers but need only n - 1 commas. This problem is similar to the task of building a fence with lengths of wire separated by posts. often called a fencepost problem If we repeatedly place a post and wire, the last post has an extra dangling wire. A flawed algorithm: for (length of fence): place some post. place some wire.

5 Fencepost loop The solution is to add an extra statement outside the loop that places the inital "post." This is sometimes also called a fencepost loop or a "loop-and-a-half" solution. The revised algorithm: place a post. for (length of fence - 1): place some wire. place some post.

6 Fencepost method solution A version of printNumbers that works: public static void printNumbers(int max) { System.out.print(1); for (int i = 2; i <= max; i++) { System.out.print(", " + i); } System.out.println(); // to end the line of output } OUTPUT from printNumbers(5) : 1, 2, 3, 4, 5

7 Fencepost practice problem Write a method named printFactors that, when given a number, prints its factors in the following format (using an example of 24 for the parameter value): [1, 2, 3, 4, 6, 8, 12, 24]

8 Fencepost practice problem Write a Java program that reads a base and a maximum power and prints all of the powers of the given base up to that max, separated by commas. Base: 2 Max exponent: 9 The first 9 powers of 2 are: 2, 4, 8, 16, 32, 64, 128, 256, 512

9 Text processing with String and char suggested reading:4.4, 3.3

10 Recall: strings and indexes The characters in a String are each internally numbered with an index, starting with 0 for the first character: String name = "M. Stepp"; index character M. Stepp Method nameDescription charAt(index)character at a specific index indexOf(String)index where the start of the given String appears in this String (-1 if it is not there) length()number of characters in this String substring(index1)characters from index1 to end of String substring(index1, index2)characters from index1 to just before index2 toLowerCase()a new String with all lowercase letters toUpperCase()a new String with all uppercase letters

11 Type char Individual text characters are represented inside a String by a primitive type called char Literal char values are surrounded with apostrophe (single- quote) marks, such as 'a' or '4' or '\n' or '\'' It is legal to have variables, parameters, returns of type char char letter = 'S'; System.out.println(letter); // S The characters of a String can be accessed as char values using the String's charAt method. String name = "Ursula McDuffee"; char firstLetter = name.charAt(0); // 'U' System.out.println(firstLetter); // U

12 Text processing text processing: Examining, editing, formatting text. Text processing often involves for loops that examine the characters of a String one by one. You can use charAt to search for or count occurrences of a particular value in a String. String title = "and all that could have been"; int count = 0; for (int i = 0; i < title.length(); i++) { char c = title.charAt(i); if (c == 'a') { System.out.println("Found an 'a' at index " + i); }

13 Other things to do with char char values can be concatenated with Strings. char initial = 'P'; System.out.println(initial + " Diddy"); char is a primitive type like int and double. You can compare char values with relational operators: 'a' < 'b' and 'Q' != 'q' An example that prints the alphabet: for (char c = 'a'; c <= 'z'; c++) { System.out.print(c); }

14 char/int and type casting All char values are assigned numbers internally by the computer, called ASCII values. For example: 'A' is 65, 'B' is 66, 'a' is 97, 'b' is 98 Mixing char and int causes automatic conversion to int. 'a' + 10 is 107, 'A' + 'A' is 130 type cast: An explicit conversion between types. General syntax: ( ) To convert an integer into the equivalent character, cast it. (char) ('a' + 10) is 'k'

15 char vs. String 'h' is a char char c = 'h'; char values are primitive; you cannot call methods on them can't say c.length() or c.toUpperCase() "h" is a string String s = "h"; Strings are objects; they contain methods that can be called can say s.length() --> 1 can say s.toUpperCase() --> "H" can say s.charAt(0) --> 'h' What is s + 1 ? What is c + 1 ? What is s + s ? What is c + c ?

16 Text processing questions Write a method named pigLatinWord that accepts a String as a parameter and outputs that word in simplified Pig Latin, by placing the word's first letter at the end followed by the suffix ay. pigLatinWord("hello") prints ello-hay pigLatinWord("goodbye") prints oodbye-gay Write methods named encode and decode that accept a String as a parameter and outputs that String with each of its letters increased or decreased by 1. encode("hello") prints ifmmp decode("ifmmp") prints hello

17 Text processing question Write a method printName that accepts a full name as a parameter, and prints the last name followed by a comma, followed by the first name and middle initial. For example, printName("James Tiberius Kirk"); would output: Kirk, James T. Method nameDescription charAt(index)character at a specific index indexOf(String)index where the start of the given String appears in this String (-1 if it is not there) length()number of characters in this String substring(index1)characters from index1 to end of String substring(index1, index2)characters from index1 to just before index2 toLowerCase()a new String with all lowercase letters toUpperCase()a new String with all uppercase letters

18 Methods with if/else suggested reading:4.5

19 if/else with return Methods can be written to return different values under different conditions using if/else statements: public static int min(int a, int b) { if (a > b) { return a; } else { return b; } An example that maps chess board squares to colors: public static Color chessBoardColor(int row, int column) { if ((row + column) % 2 == 0) { return Color.WHITE; } else { return Color.BLACK; }

20 More examples Another example that returns the first word in a String: public static String firstWord(String s) { int index = s.indexOf(" "); if (index >= 0) { return s.substring(0, index); } else { // only one word in String return s; } It is an error not to return a value in every path: public static int min(int a, int b) { if (a > b) { return a; } // Error; not all code paths return a value. // Vhat if b >= a ? }

21 for loops with if/else return Methods with loops that return values must consider the case where the loop does not execute the return. public static int indexOf(String s, char c) { for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == c) { return i; } } // error; what if c does not occur in s? } A better version that returns -1 when c is not found: public static int indexOf(String s, char c) { for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == c) { return i; } } return -1; // not found }

22 if/else return question Write a method named numUnique that accepts two integers as parameters and returns how many unique values were passed. For example, numUnique(3, 7) returns 2 because 3 and 7 are two unique numbers, but numUnique(4, 4) returns 1 because 4 and 4 only represent one unique number. Write a method named countFactors that returns the number of factors of an integer. For example, countFactors(60) returns 11 because 1, 2, 3, 4, 5, 6, 10, 15, 20, 30, and 60 are factors of 60. Modify the pigLatinWord and encode / decode methods seen previously so that they return their results rather than printing them.

23 Method return question Write a program that prompts the user for a maximum integer and prints out a list of all prime numbers up to that maximum. Here is an example log of execution: Maximum number? 50 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, total primes