Chapter 5 Branches

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

"Apples", "Oranges"

'A' is less-than 'O'

Given userText is "March 17, 2034". What character does userText.charAt(userText.length() - 1) return?

4 That's one way to get the last character.

nested if-else

A branch's statements can include any valid statements, including another if-else statement, such occurrence known as nested if-else statements. if (userChar == 'q') { // userChar 'q' ... } else if (userChar == 'c') { if (numItems < 0) { // userChar 'c' and numItems < 0 ... } else { // userChar 'c' and numItems >= 0 ... } } else { // userChar not 'q' or 'c' ... }

Logical operators

A logical operator treats operands as being true or false, and evaluates to true or false.

String access operations

A string is a sequence of characters in memory. Each string character has a position number called an index. The numbering starts with 0, not 1. charAt(): The notation someString.charAt(0) determines the character at a particular index of a string, in this case index 0.

5.5 Switch statements

A switch statement can more clearly represent multi-branch behavior involving a variable being compared to constant values. The program executes the first case whose constant expression matches the value of the switch expression, executes that case's statements, and then jumps to the end. If no case matches, then the default case statements are executed.

if-else

An if-else expression commonly involves a relational operator or equality operator.

Boolean

Boolean refers to a quantity that has only two possible values, true or false. Java has the built-in data type boolean for representing Boolean quantities.

Multiple if-else branches

Commonly, a programmer requires more than two branches, in which case a multi-branch if-else arrangement can be used. if (expr1) { } else if (expr2) { } ... else if (exprN) { } else { }

concat(moreString)

Creates a new String that appends the String moreString at the end. // userText is "Hi" userText = userText.concat(" friend"); // Now "Hi friend" newText = userText.concat(" there"); // newText is "Hi friend there"

Given: float x, y x == y is OK.

False Floating-point numbers should not use == for comparison, due to inexact representation.

To what value does each evaluate? userStr is "Hey #1?". Character.isDigit(userStr.charAt(6))

False That character is '?'.

Given: double x, y x == y is OK.

False Variables of type double are floating-point numbers, which should not use ==.

Given: double x x == 32.0 is OK.

False x and 32.0 are floating-point numbers, which should not use ==.

Floating-point comparison

Floating-point numbers should not be compared using ==. Ex: Avoid float1 == float2. Reason: Some floating-point numbers cannot be exactly represented in the limited available memory bits like 64 bits. Floating-point numbers expected to be equal may be close but not exactly equal. Floating-point numbers should be compared for "close enough" rather than exact equality. Ex: If (x - y) < 0.0001, x and y are deemed equal. Because the difference may be negative, the absolute value is used: Math.abs(x - y) < 0.0001. Math.abs() is a method in the Math class. The difference threshold indicating that floating-point numbers are equal is often called the epsilon. Epsilon's value depends on the program's expected values, but 0.0001 is common.

"banana", "bananarama"

If existing characters are equal, the shorter string is less-than.

Conditional expressions

If-else statements with the form shown below are so common that the language supports the shorthand notation shown.

Given userText is "Think". What character is at index 1 of userText?

Index numbering starts with 0. T is at index 0, h is at index 1.

indexOf(item) > detect CensoredWords

Index of first item occurrence, else -1. Item may be char, String variable, or string literal. indexOf(item, indx) starts at index indx. lastIndexOf(item) finds the last occurrence . // userText is "Help me!" userText.indexOf('p') // Returns 3 userText.indexOf('e') // Returns 1 (first occurrence) userText.indexOf('z') // Returns -1 userText.indexOf("me") // Returns 5 userText.indexOf('e', 2) // Returns 6 (starts at index 2) userText.lastIndexOf('e') // Returns 6 (last occurrence)

a && b (Given age = 19, days = 7, userChar = 'q')

Logical AND: true when both of its operands are true (age > 16) && (age < 25) >true, because both operands are true.

!a (Given age = 19, days = 7, userChar = 'q')

Logical NOT (opposite): true when its single operand is false (and false when operand is true) !(days > 10) >true, because operand is false. !(age > 16) >false, because operand is true. !(userChar == 'q') >false, because operand is true.

a || b (Given age = 19, days = 7, userChar = 'q')

Logical OR: true when at least one of its two operands are true (age > 16) || (days > 10) >true, because at least one operand is true (age > 16 is true).

myString == "Hello"

Not OK Compiles, but does not behave as expected. String comparisons are discussed later.

myDouble == 3.25

Not OK Compiles, but due to imprecision of floating-point representations, such comparisons may yield unexpected results. More later; for now, just don't compare floating-point types.

Table 5.7.1: str1.compareTo(str2) return values.

Relation Returns Expression to detect str1 less-than str2---Negative number---str1.compareTo(str2) < 0 str1 equal-to str2---0---str1.compareTo(str2) == 0 str1 greater-than str2---Positive number---str1.compareTo(str2) > 0

Table 5.2.1: Relational (first four) and equality (last two) operators.

Relational and equality operators Description a < b a is less-than b a > b a is greater-than b a <= b a is less-than-or-equal-to b a >= b a is greater-than-or-equal-to b a == b a is equal to b a != b a is not equal to b

replace(findStr, replaceStr) replace(findChar, replaceChar)

Returns a new String in which all occurrences of findStr (or findChar) have been replaced with replaceStr (or replaceChar). // userText is "Hello" userText = userText.replace('H', 'j'); // Now "jello" // userText is "You have many gifts" userText = userText.replace("many", "a plethora of"); // Now "You have a plethora of gifts" // userText is "Goodbye" newText = userText.replace("bye"," evening"); // newText is "Good evening"

substring(startIndex, endIndex

Returns substring starting at startIndex and ending at endIndex - 1. The length of the substring is given by endIndex - startIndex. // userText is "http://google.com" userText.substring(0, 7) // Returns "http://" userText.substring(13, 17) // Returns ".com" userText.substring(userText.length() - 4, userText.length()) // Last 4: ".com" ---------------------- Begin the extraction at position 2, and extract the rest of the string: var str = "Hello world!"; var res = str.substring(2); The result of res will be: llo world!

Multiple distinct if statements

Sometimes the programmer has multiple if statements in sequence, which looks similar to a multi-branch if-else statement but has a very different meaning. Each if-statement is independent, and thus more than one branch can execute, in contrast to the multi-branch if-else arrangement.

Character operations

Table 5.10.1: Character methods return values. Each method must prepend Character., as in Character.isLetter. isLetter(c) true if alphabetic: a-z or A-Z isLetter('x') // true isLetter('6') // false isLetter('!') // false toUpperCase(c) Uppercase version toUpperCase('a') // A toUpperCase('A') // A toUpperCase('3') // 3 isDigit(c) true if digit: 0-9. isDigit('x') // false isDigit('6') // true toLowerCase(c) Lowercase version toLowerCase('A') // a toLowerCase('a') // a toLowerCase('3') // 3 isWhitespace(c) true if whitespace. isWhitespace(' ') // true isWhitespace('\n') // true isWhitespace('x') // false

String modify operations

Table 5.9.1: String modify methods, invoked as someString.concat(moreString). Each returns a new String of the appropriate length.

"merry", "Merry"

The coded value for 'm' is greater-than the coded value for 'M'

To what value does each evaluate? userStr is "Hey #1?". Character.isLetter(userStr.charAt(0))

True 'H' is alphabetic.

String comparisons

Two strings are commonly compared for equality. Equal strings have the same number of characters, and each corresponding character is identical. 'A' is 65, B' is 66, etc., while 'a' is 97, 'b' is 98, etc. So "Apples" is less than "apples" or "abyss" because 'A' is less than 'a'. "Zoology" is less than "apples". A common error is to forget that case matters in a string comparison. java expression example: if(userString.equals("Quit")) if(firstString.compareTo(secondString) <= 0)

This if-else form can be written as a conditional expression.

if (condition) { myVar = expr1; } else { myVar = expr2; } ---------------------------------- myVar = (condition) ? expr1 : expr2

A switch statement can be written using a multi-branch if-else statement, but the switch statement may make the programmer's intent clearer.

if (dogYears == 0) { // Like case 0 // Print 0..14 years } else if (dogYears == 1) { // Like case 1 // Print 15 years } ... else if (dogYears == 5) { // Like case 5 // Print 37 years } else { // Like default case // Print unknown }

Complete the code by comparing string variables myName and yourName. Start with myName.

if(myName.compareTo(yourName)>0 { System.out.print(myName + " is greater."); }

String info methods length()

length() Number of characters // userText is "Help me!" userText.length() // Returns 8 // userText is "" userText.length() // Returns 0

Given userText is "Think". To what character does this evaluate: userText.charAt(3)

n Indexes start with 0, so 3 corresponds to the 4th character (0, 1, 2, *3*).

numDogs is either less-than or greater-than numCats

numDogs != numCats

switch statement

The switch statement's expression should be an integer, char, or string (discussed elsewhere). The expression should not be a Boolean or a floating-point type. Each case must have a constant expression like 2 or 'q'; a case expression cannot be a variable.

switch statement example

switch (userChar) { case 'A': encodedVal = 1; break; case 'B': encodedVal = 2; break; case 'C': case 'D': encodedVal = 4; break; case 'E': encodedVal = 5; case 'F': encodedVal = 6; break; default: encodedVal = -1; break; }

isEmpty()

true if length is 0 // userText is "Help me!" userText.isEmpty() // Returns false // userText is "" userText.isEmpty() // Returns true

userChar is the character 'x'.

userChar == 'x'

Braces

{ }, sometimes redundantly called curly braces, represent a grouping, such as a grouping of statements. Note: { } are braces, [ ] are brackets.


Kaugnay na mga set ng pag-aaral

AP Final lets go win this test yeah

View Set

6.RP.3 Ratio Tools and Proportional Relationships

View Set

week 9 carmen quiz: continuous random variables

View Set

Pharmacology Exam II Review Questions

View Set

Chapter 11 Soil: Foundation for Land Ecosystems

View Set