copyright 2006 by pearson education 1 building java programs chapter 4: conditional execution

68
1 Copyright 2006 by Pearson Education Building Java Building Java Programs Programs Chapter 4: Conditional Execution

Post on 20-Dec-2015

216 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

1Copyright 2006 by Pearson Education

Building Java Building Java ProgramsPrograms

Chapter 4: Conditional Execution

Page 2: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

2Copyright 2006 by Pearson Education

Chapter outline loop techniques

cumulative sum fencepost loops

conditional execution the if statement and the if/else statement relational expressions nested if/else statements

subtleties of conditional execution object equality factoring if/else code text processing methods with conditional execution: revisiting return values

Page 3: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

3Copyright 2006 by Pearson Education

reading: 4.1

Cumulative sumCumulative sum

Page 4: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

4Copyright 2006 by Pearson Education

Adding many numbers Consider this code to read and add three values:

Scanner console = new Scanner(System.in);System.out.print("Type a number: ");int num1 = console.nextInt();

System.out.print("Type a number: ");int num2 = console.nextInt();

System.out.print("Type a number: ");int num3 = console.nextInt();

int sum = num1 + num2 + num3;System.out.println("The sum is " + sum);

Page 5: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

5Copyright 2006 by Pearson Education

A cumulative sum The variables num1, num2, and num3 are unnecessary:

Scanner console = new Scanner(System.in);System.out.print("Type a number: ");int sum = console.nextInt();

System.out.print("Type a number: ");sum += console.nextInt();

System.out.print("Type a number: ");sum += console.nextInt();

System.out.println("The sum is " + sum);

cumulative sum: A variable that keeps a sum-in-progress and is updated many times until the task of summing is finished.

The variable sum in the above code is a cumulative sum.

Page 6: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

6Copyright 2006 by Pearson Education

Failed cumulative sum loop How could we modify the code to sum 100 numbers?

Creating 100 copies of the same code would be redundant.

An incorrect solution:Scanner console = new Scanner(System.in);for (int i = 1; i <= 100; i++) { int sum = 0; System.out.print("Type a number: "); sum += console.nextInt();}

// sum is undefined hereSystem.out.println("The sum is " + sum);

The scope of sum is inside the for loop, so the last line of code fails to compile.

Page 7: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

7Copyright 2006 by Pearson Education

Fixed cumulative sum loop A corrected version of the sum loop code:

Scanner console = new Scanner(System.in);int sum = 0;for (int i = 1; i <= 100; i++) { System.out.print("Type a number: "); sum += console.nextInt();}System.out.println("The sum is " + sum);

The key idea: Cumulative sum variables must always be declared outside the

loops that update them, so that they will continue to live after the loop is finished.

Page 8: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

8Copyright 2006 by Pearson Education

User-guided cumulative sum User input can control the number of loop repetitions:

Scanner console = new Scanner(System.in);System.out.print("How many numbers to add? ");int count = console.nextInt();

int sum = 0;for (int i = 1; i <= count; i++) { System.out.print("Type a number: "); sum += console.nextInt();}System.out.println("The sum is " + sum);

An example output:

How many numbers to add? 3Type a number: 2Type a number: 6Type a number: 3The sum is 11

Page 9: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

9Copyright 2006 by Pearson Education

Variation: cumulative product The same idea can be used with other operators, such

as multiplication which produces a cumulative product:

Scanner console = new Scanner(System.in);System.out.print("Raise 2 to what power? ");int exponent = console.nextInt();

int product = 1;for (int i = 1; i <= exponent; i++) { product = product * 2;}System.out.println("2 to the " + exponent + " = " + product);

Exercises: Change the above code so that it also prompts for the base,

instead of always using 2. Change the above code into a method which accepts a base a

and exponent b as parameters and returns ab.

Page 10: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

10Copyright 2006 by Pearson Education

Cumulative sum question Write a program that reads input of the number of hours

two employees have worked and displays each employee's total and the overall total hours.

The company doesn't pay overtime, so cap any day at 8 hours.

Example log of execution:Employee 1: How many days? 3Hours? 6Hours? 12Hours? 5Employee 1's total hours = 19

Employee 2: How many days? 2Hours? 11Hours? 6Employee 2's total hours = 14

Total hours for both = 33

Page 11: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

11Copyright 2006 by Pearson Education

Cumulative sum answer// Computes the total paid hours worked by two employees.// The company does not pay for more than 8 hours per day.// Uses a "cumulative sum" loop to compute the total hours.

import java.util.*;

public class Hours { public static void main(String[] args) { Scanner console = new Scanner(System.in); int hours1 = processEmployee(console, 1); int hours2 = processEmployee(console, 2); int total = hours1 + hours2; System.out.println("Total hours for both = " + total); } ...

Page 12: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

12Copyright 2006 by Pearson Education

Cumulative sum answer 2 ...

// Reads hours information about one employee with the given number.

// Returns the total hours worked by the employee. public static int processEmployee(Scanner console, int number) { System.out.print("Employee " + number + ": How many days? "); int days = console.nextInt(); // totalHours is a cumulative sum of all days' hours worked. int totalHours = 0; for (int i = 1; i <= days; i++) { System.out.print("Hours? "); int hours = console.nextInt(); totalHours += Math.min(hours, 8); // cap at 8 hours/day } System.out.println("Employee " + number + "'s total hours = " + totalHours); System.out.println(); return totalHours; }}

Page 13: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

13Copyright 2006 by Pearson Education

reading: 4.1

Fencepost loopsFencepost loops

Page 14: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

14Copyright 2006 by Pearson Education

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

Page 15: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

15Copyright 2006 by Pearson Education

Flawed solution 1 A flawed solution:

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,

Page 16: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

16Copyright 2006 by Pearson Education

Flawed solution 2 Another flawed solution:

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

Page 17: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

17Copyright 2006 by Pearson Education

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 will have an extra dangling wire.

A flawed algorithm:for (length of fence) { place some post. place some wire.}

Page 18: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

18Copyright 2006 by Pearson Education

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.}

Page 19: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

19Copyright 2006 by Pearson Education

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

Page 20: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

20Copyright 2006 by Pearson Education

Fencepost question 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]

Page 21: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

21Copyright 2006 by Pearson Education

Fencepost question 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

Page 22: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

22Copyright 2006 by Pearson Education

reading: 4.2

if/else statementsif/else statements

Page 23: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

23Copyright 2006 by Pearson Education

The if statement if statement: A Java statement that executes a block

of statements only if a certain condition is true. If the condition is not true, the block of statements is skipped. General syntax:if (<condition>) { <statement> ; <statement> ; ... <statement> ;}

Example:double gpa = console.nextDouble();if (gpa >= 2.0) { System.out.println("Your application is accepted.");}

Page 24: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

24Copyright 2006 by Pearson Education

if statement flow diagram

Page 25: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

25Copyright 2006 by Pearson Education

The if/else statement if/else statement: A Java statement that executes

one block of statements if a certain condition is true, and a second block of statements if it is false.

General syntax:if (<condition>) { <statement(s)> ;} else { <statement(s)> ;}

Example:double gpa = console.nextDouble();if (gpa >= 2.0) { System.out.println("Welcome to Mars University!");} else { System.out.println("Your application is denied.");}

Page 26: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

26Copyright 2006 by Pearson Education

if/else flow diagram

Page 27: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

27Copyright 2006 by Pearson Education

Relational expressions The <condition> used in an if or if/else statement is

the same kind seen in a for loop.for (int i = 1; i <= 10; i++) {

The conditions are actually of type boolean, seen in Ch. 5.

These conditions are called relational expressions and use one of the following six relational operators:

Operator Meaning Example Value

== equals 1 + 1 == 2 true

!= does not equal 3.2 != 2.5 true

< less than 10 < 5 false

> greater than 10 > 5 true

<= less than or equal to 126 <= 100 false

>= greater than or equal to 5.0 >= 5.0 true

Page 28: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

28Copyright 2006 by Pearson Education

Evaluating rel. expressions Relational operators have lower precedence than math operators.

Example:

5 * 7 >= 3 + 5 * (7 - 1)

5 * 7 >= 3 + 5 * 6

35 >= 3 + 30

35 >= 33

true

Relational operators cannot be "chained" as they can in algebra. Example:

2 <= x <= 10

true <= 10

error!

Page 29: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

29Copyright 2006 by Pearson Education

if/else question Write code to read a number from the user and print

whether it is even or odd using an if/else statement.

Example executions:

Type a number: 42

Your number is even

Type a number: 17

Your number is odd

Page 30: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

30Copyright 2006 by Pearson Education

Loops with if/else Loops can be used with if/else statements:

int nonnegatives = 0, negatives = 0;for (int i = 1; i <= 10; i++) { int next = console.nextInt(); if (next >= 0) { nonnegatives++; } else { negatives++; }}

public static void printEvenOdd(int max) { for (int i = 1; i <= max; i++) { if (i % 2 == 0) { System.out.println(i + " is even"); } else { System.out.println(i + " is odd"); } }}

Page 31: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

31Copyright 2006 by Pearson Education

Nested if/else statements nested if/else statement: A chain of if/else that

chooses between outcomes using many conditions. General syntax:if (<condition>) { <statement(s)> ;} else if (<condition>) { <statement(s)> ;} else { <statement(s)> ;}

Example:if (number > 0) { System.out.println("Positive");} else if (number < 0) { System.out.println("Negative");} else { System.out.println("Zero");}

Page 32: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

32Copyright 2006 by Pearson Education

Nested if/else variations A nested if/else can end with an if or an else.

If it ends with else, one of the code paths must be taken. If it ends with if, the program might not execute any path.

Example ending with if:if (place == 1) { System.out.println("You win the gold medal!");} else if (place == 2) { System.out.println("You win a silver medal!");} else if (place == 3) { System.out.println("You earned a bronze medal.");}

Are there any cases where this code will not print a message? How could we modify it to print a message to non-medalists?

Page 33: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

33Copyright 2006 by Pearson Education

Nested if/else flow diagramif (<condition>) { <statement(s)> ;} else if (<condition>) { <statement(s)> ;} else { <statement(s)> ;}

Page 34: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

34Copyright 2006 by Pearson Education

Nested if/else/if diagramif (<condition>) { <statement(s)> ;} else if (<condition>) { <statement(s)> ;} else if (<condition>) { <statement(s)> ;}

Page 35: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

35Copyright 2006 by Pearson Education

Sequential if diagramif (<condition>) { <statement(s)> ;}if (<condition>) { <statement(s)> ;}if (<condition>) { <statement(s)> ;}

Page 36: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

36Copyright 2006 by Pearson Education

Structures of if/else code Choose 1 of many paths:

(conditions are mutually exclusive)

if (<condition>) { <statement(s)>;} else if (<condition>) { <statement(s)>;} else { <statement(s)>;}

Choose 0 or 1 of many paths:(conditions are mutually exclusive and any action is optional)

if (<condition>) { <statement(s)>;} else if (<condition>) { <statement(s)>;} else if (<condition>) { <statement(s)>;}

Choose 0, 1, or many of many paths:(conditions/actions are independent of each other)

if (<condition>) { <statement(s)>;}if (<condition>) { <statement(s)>;} if (<condition>) { <statement(s)>;}

Page 37: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

37Copyright 2006 by Pearson Education

Which nested if/else to use? Which if/else construct is most appropriate?

Reading the user's GPA and printing whether the student is on the dean's list (3.8 to 4.0) or honor roll (3.5 to 3.8).

Printing whether a number is even or odd.

Printing whether a user is lower-class, middle-class, or upper-class based on their income.

Reading a number from the user and printing whether it is divisible by 2, 3, and/or 5.

Printing a user's grade of A, B, C, D, or F based on their percentage in the course.

Page 38: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

38Copyright 2006 by Pearson Education

Which nested if/else answers Which if/else construct is most appropriate?

Reading the user's GPA and printing whether the student is on the dean's list (3.8 to 4.0) or honor roll (3.5 to 3.8).

nested if / else if Printing whether a number is even or odd.

simple if / else Printing whether a user is lower-class, middle-class, or upper-

class based on their income. nested if / else if / else

Reading a number from the user and printing whether it is divisible by 2, 3, and/or 5.

sequential if / if / if Printing a user's grade of A, B, C, D, or F based on their

percentage in the course. nested if / else if / else if / else if / else

Page 39: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

39Copyright 2006 by Pearson Education

How to comment: if/else Comments shouldn't describe the condition being tested.

Instead, describe why you are performing that test, or what you intend to do based on its result.

Bad example:// Test whether student 1's GPA is better than student 2'sif (gpa1 > gpa2) { // print that student 1 had the greater GPA System.out.println("The first student had the greater GPA.");} else if (gpa2 > gpa1) { // print that student 2 had the greater GPA System.out.println("The second student's GPA was higher.");} else { // there was a tie System.out.println("There has been a tie!");}

Better example:// Print a message about which student had the higher grade point average.if (gpa1 > gpa2) { System.out.println("The first student had the greater GPA.");} else if (gpa2 > gpa1) { System.out.println("The second student's GPA was higher.");} else { // gpa1 == gpa2 (a tie) System.out.println("There has been a tie!");}

Page 40: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

40Copyright 2006 by Pearson Education

How to comment: if/else 2 Sometimes putting comments on the if/else bodies

themselves is more helpful. Example:if (guessAgain == 1) { // user wants to guess again; reset game state // and start another game System.out.println("Playing another game."); score = 0; resetGame(); play();} else { // user is finished playing; print their best score System.out.println("Thank you for playing."); System.out.println("Your score was " + score);}

Page 41: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

41Copyright 2006 by Pearson Education

Math.max/min vs. if/else Many if/else statements that choose the larger or

smaller of 2 numbers can be replaced by a call to Math.max or Math.min.

int z; // z should be larger of x, yif (x > y) { z = x;} else { z = y;}

int z = Math.max(x, y);

double d = a; // d should be smallest of a, b, cif (b < d) { d = b;}if (c < d) { d = c;}

double d = Math.min(a, Math.min(b, c));

Page 42: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

42Copyright 2006 by Pearson Education

reading: 4.3

Subtleties of Subtleties of conditional executionconditional execution

Page 43: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

43Copyright 2006 by Pearson Education

Comparing objects Relational operators such as < and == only behave

correctly on primitive values.

The == operator on Strings often evaluates to false even when the Strings have the same letters in them.

Example (incorrect):

Scanner console = new Scanner(System.in);System.out.print("What is your name? ");String name = console.next();if (name == "Barney") { System.out.println("I love you, you love me,"); System.out.println("We're a happy family!");}

This example code will compile, but it will never print the message, even if the user does type Barney

Page 44: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

44Copyright 2006 by Pearson Education

The equals method Objects (such as String, Point, and Color) should be

compared for equality by calling a method named equals.

Example (correct):

Scanner console = new Scanner(System.in);System.out.print("What is your name? ");String name = console.next();if (name.equals("Barney")) { System.out.println("I love you, you love me,"); System.out.println("We're a happy family!");}

Page 45: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

45Copyright 2006 by Pearson Education

Another example The == operator on objects actually compares whether two

variables refer to the same object. The equals method compares whether two objects have the same

state as each other.

Given the following code:

Point p1 = new Point(3, 8);Point p2 = new Point(2, -4);Point p3 = p2;

What is printed?

if (p1 == p2) { System.out.println("1");}if (p1.equals(p2)) { System.out.println("2");}if (p2 == p3) { System.out.println("3");}

x 3 y 8p1

x 2 y -4p2

p3

Page 46: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

46Copyright 2006 by Pearson Education

String condition methods There are several methods of a String object that can

be used as conditions in if statements:

Method Description

equals(str) whether two strings contain exactly the same characters

equalsIgnoreCase(str) whether two strings contain the same characters, ignoring upper vs. lower case differences

startsWith(str) whether one string contains the other's characters at its start

endsWith(str) whether one string contains the other's characters at its end

Page 47: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

47Copyright 2006 by Pearson Education

String condition examples Hypothetical examples, assuming the existence of

various String variables: if (title.endsWith("Ph. D.")) { System.out.println("How's life in the ivory tower?");}

if (fullName.startsWith("Queen")) { System.out.println("Greetings, your majesty.");}

if (lastName.equalsIgnoreCase("lumberg")) { System.out.println("I need your TPS reports!");}

if (name.toLowerCase().indexOf("jr.") >= 0) { System.out.println("You share your parent's name.");}

Page 48: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

48Copyright 2006 by Pearson Education

Factoring if/else code factoring: extracting common/redundant code

Factoring if/else code reduces the size of the if and else statements and can sometimes eliminate the need for if/else altogether.

Example:

int x;

if (a == 1) {

x = 3;

} else if (a == 2) {

x = 5;

} else { // a == 3

x = 7;

}

int x = 2 * a + 1;

Page 49: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

49Copyright 2006 by Pearson Education

Code in need of factoring The following example has a lot of redundant code:

if (money < 500) { System.out.println("You have, $" + money + " left."); System.out.print("Caution! Bet carefully."); System.out.print("How much do you want to bet? "); bet = console.nextInt();} else if (money < 1000) { System.out.println("You have, $" + money + " left."); System.out.print("Consider betting moderately."); System.out.print("How much do you want to bet? "); bet = console.nextInt();} else { System.out.println("You have, $" + money + " left."); System.out.print("You may bet liberally."); System.out.print("How much do you want to bet? "); bet = console.nextInt();}

Page 50: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

50Copyright 2006 by Pearson Education

Code after factoring Factoring tips:

If the start of each branch is the same, move it before the if/else. If the end of each branch is the same, move it after the if/else.

System.out.println("You have, $" + money + " left.");

if (money < 500) { System.out.print("Caution! Bet carefully.");} else if (money < 1000) { System.out.print("Consider betting moderately.");} else { System.out.print("You may bet liberally.");}

System.out.print("How much do you want to bet? ");bet = console.nextInt();

Page 51: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

51Copyright 2006 by Pearson Education

reading: 4.4

Text processingText processingwith String and charwith String and char

Page 52: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

52Copyright 2006 by Pearson Education

Type char char: A primitive type representing single characters.

Individual characters inside a String are stored as char values. 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

Page 53: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

53Copyright 2006 by Pearson Education

The charAt method The characters of a string can be accessed as char values using the String object's charAt method.

String word = console.next();char firstLetter = word.charAt(0);if (firstLetter == 'c') { System.out.println("That's good enough for me!");}

We often use for loops that print or examine each character.

String name = "tall";for (int i = 0; i < name.length(); i++) { System.out.println(title.charAt(i));}

Output:tall

Page 54: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

54Copyright 2006 by Pearson Education

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.

// Returns the count of occurrences of c in s.public static int count(String s, char c) { int count = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == 't') { count++; } } return count;}

count("mississippi", 'i') returns 4

Page 55: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

55Copyright 2006 by Pearson Education

Other things to do with char char values can be concatenated with strings.

char initial = 'P';

System.out.println(initial + " Diddy");

You can compare char values with relational operators: 'a' < 'b' and 'Q' != 'q' Note that you cannot use these operators on a String.

An example that prints the alphabet:for (char c = 'a'; c <= 'z'; c++) {

System.out.print(c);

}

Page 56: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

56Copyright 2006 by Pearson Education

char/int and type casting All char values are assigned numbers internally by the

computer, called ASCII values.

Examples:'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

To convert an integer into the equivalent character, type cast it.(char) ('a' + 2) is 'c'

Page 57: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

57Copyright 2006 by Pearson Education

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 StringString 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 ?

Page 58: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

58Copyright 2006 by Pearson Education

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

Page 59: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

59Copyright 2006 by Pearson Education

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 name Description

charAt(index) character at a specific index

indexOf(str) 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, index2) the characters in this string from index1 (inclusive) to index2 (exclusive)

toLowerCase() a new string with all lowercase letters

toUpperCase() a new string with all uppercase letters

Page 60: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

60Copyright 2006 by Pearson Education

reading: 4.5

Methods with if/elseMethods with if/else

Page 61: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

61Copyright 2006 by Pearson Education

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; }}

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; }}

Page 62: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

62Copyright 2006 by Pearson Education

All code paths must return It is an error not to return a value in every path:

public static int min(int a, int b) { if (a > b) { return b; } // Error; not all paths return a value. What if a <= b ?}

Two fixed versions of the code:public static int min(int a, int b) { if (a > b) { return b; } else { return a; }}

public static int min(int a, int b) { if (a > b) { return b; } return a;}

Page 63: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

63Copyright 2006 by Pearson Education

All code paths must return 2 The following code also does not compile:

public static int min(int a, int b) {

if (a >= b) {

return b;

} else if (a < b) {

return a;

}

}

It produces the "Not all paths return a value" error. To our eyes, it seems that all paths do return a value. But the compiler thinks that if/else/if code might choose not

to execute any branch, so it refuses to accept this code.

Page 64: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

64Copyright 2006 by Pearson Education

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}

Page 65: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

65Copyright 2006 by Pearson Education

if/else return question Write a method named numUnique that accepts two

integer 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.

Page 66: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

66Copyright 2006 by Pearson Education

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

Page 67: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

67Copyright 2006 by Pearson Education

Method return answer 1// Prompts for a maximum number and prints each prime up to that maximum.import java.util.*;

public class Primes { public static void main(String[] args) { // read max from user Scanner console = new Scanner(System.in); System.out.print("Maximum number? "); int max = console.nextInt(); printAllPrimes(max); }

public static void printAllPrimes(int max) { System.out.print(2); // print first prime (fencepost)

// A loop to print the rest of the prime numbers. int primes = 1; for (int i = 3; i <= max; i++) { if (countFactors(i) == 2) { // i is prime System.out.print(", " + i); primes++; } }

System.out.println(); System.out.println(primes + " total primes"); }

Page 68: Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution

68Copyright 2006 by Pearson Education

Method return answer 2 ...

// Returns how many factors the given number has. public static int countFactors(int number) { int count = 0; for (int i = 1; i <= number; i++) { if (number % i == 0) { count++; // i is a factor of number } } return count; }}