Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 1 Fencepost loops suggested reading:4.1

2 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 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 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 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 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 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 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 9 Text processing with String and char suggested reading:4.4, 3.3

10 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"; index01234567 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 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 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 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 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 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 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 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 18 Methods with if/else suggested reading:4.5

19 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 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 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 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 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, 47 14 total primes


Download ppt "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."

Similar presentations


Ads by Google