Chapter 4 Characters Strings and Mathematical Functions Objectives

Chapter 4: Characters, Strings, and Mathematical Functions

Objectives To solve mathematics problems by using the methods in the Math class (§ 4. 2). To represent characters using the char type (§ 4. 3). To encode characters using ASCII and Unicode (§ 4. 3. 1). To represent special characters using the escape sequences (§ 4. 4. 2). To cast a numeric value to a character and cast a character to an integer (§ 4. 3. 3). To compare and test characters using the static methods in the Character class (§ 4. 3. 4). To introduce objects and instance methods (§ 4. 4). To represent strings using the String objects (§ 4. 4). To return the string length using the length() method (§ 4. 4. 1). To return a character in the string using the char. At(i) method (§ 4. 4. 2). To use the + operator to concatenate strings (§ 4. 4. 3). To read strings from the console (§ 4. 4. 4). To read a character from the console (§ 4. 4. 5). To compare strings using the equals method and the compare. To methods (§ 4. 4. 6). To obtain substrings (§ 4. 4. 7). To find a character or a substring in a string using the index. Of method (§ 4. 4. 8). To program using characters and strings (Guess. Birthday) (§ 4. 5. 1). To convert a hexadecimal character to a decimal value (Hex. Digit 2 Dec) (§ 4. 5. 2). To revise the lottery program using strings (Lottery. Using. Strings) (§ 4. 5. 3). To format output using the System. out. printf method (§ 4. 6). © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 2

Motivations Suppose you need to estimate the area enclosed by four cities, given the GPS locations (latitude and longitude) of these cities, as shown in the following diagram. – How would you write a program to solve this problem? You will be able to write such a program after completing this chapter. © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 3

Motivations Summary: – This chapter introduced additional basic features of Java These features include Strings, Characters, and additional Mathematical Functions – Java provides many useful methods in the Math class for performing common mathematical functions. © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 4

Common Mathematical Functions Method: – A group of statements that performs a specific task – You have already seen several methods: pow(a, b): to compute ab random(): generate a random number – Both of these methods are inside the Math class – There are many other beneficial methods inside the Math class as well © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 5

The Math Class constants: – PI –E You can use these constants as Math. PI and Math. E in any program. Class methods can be categorized as: – Trigonometric Methods – Exponent Methods – Service methods rounding, min, max, abs, and random Methods © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 6

Trigonometric Methods The parameter of sin, cos, and tan is an angle in radians The return value of asin, acos, and atan is a degree in radians © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 7

Trigonometric Methods Examples: Math. to. Degrees(Math. PI / 2); //returns 90. 0 Math. to. Radians(30); //returns 0. 5236 (same as π/6) Math. sin(0); //returns 0. 0 Math. sin(Math. to. Radians(270)); // returns -1. 0 Math. sin(Math. PI / 6); // returns 0. 5 Math. sin(Math. PI / 2); // returns 1. 0 Math. cos(0); // returns 1. 0 Math. cos(Math. PI / 6); // returns 0. 866 Math. cos(Math. PI / 2); // returns 0 Math. asin(0. 5); // returns 0. 523598333 (same as π/6) Math. acos(0. 5); //returns 1. 0472 (same as π/3) Math. atan(1. 0); // returns 0. 785398 (same as π/4) © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 8

Exponent Methods © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 9

Exponent Methods Examples: Math. exp(1); // returns 2. 71828 Math. log(Math. E); // returns 1. 0 Math. log 10(10); // returns 1. 0 Math. pow(2, 3); // returns 8. 0 Math. pow(3, 2); // returns 9. 0 Math. pow(4. 5, 2. 5); // returns 22. 91765 Math. sqrt(4); // returns 2. 0 Math. sqrt(10. 5); // returns 4. 24 © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 10

Rounding Methods Math class contains five rounding methods: – double ceil(double x) x rounded up to its nearest integer. This integer is returned as a double value. – double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value. – double rint(double x) x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double. – int round(float x) Return (int)Math. floor(x+0. 5). – long round(double x) Return (long)Math. floor(x+0. 5). © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 11

Rounding Methods Examples: Math. ceil(2. 1); Math. ceil(2. 0); Math. ceil(-2. 1); Math. floor(2. 0); Math. floor(-2. 1); Math. rint(2. 0); Math. rint(-2. 1); Math. rint(2. 5); Math. rint(-2. 5); Math. round(2. 6 f); Math. round(2. 0); Math. round(-2. 0 f); Math. round(-2. 6); © Dr. Jonathan Cazalas //returns //returns //returns //returns //returns 3. 0 2. 0 – 2. 0 -2. 0 – 2. 0 -3. 0 2. 0 – 2. 0 -2. 0 3 2 -2 -3 Chapter 4: Characters, Strings, and Mathematical Functions page 12

min, max, and abs min and max methods – min(a, b): returns minimum of a and b – max(a, b): returns the maximum of a and b abs method: – abs(a): returns the absolute value of a Examples: Math. max(2, 3); Math. max(2. 5, 3); Math. min(2. 5, 4. 6); Math. abs(-2. 1); © Dr. Jonathan Cazalas //returns //returns 3 3 2. 5 2 2. 1 Chapter 4: Characters, Strings, and Mathematical Functions page 13

The random Method Generates a random double value – This value is greater than or equal to 0. 0 and less than 1. 0 0 <= Math. random() < 1. 0 – Examples: (int)(Math. random() * 10); – returns a random integer between 0 and 9 50 + (int)(Math. random() * 50); – returns a random integer between 50 and 99 a + Math. random() * b; – returns a random number between a and a+b, excluding a+b © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 14

Evaluate the following method calls: a. Math. sqrt(4) b. Math. pow(2, 3) c. Math. rint(-2. 5) d. Math. ceil(7. 1) e. Math. ceil(-2. 8) f. Math. floor(-2. 2) g. Math. floor(9. 9) h. Math. round(2. 5) i. Math. round(Math. abs(-3. 5)) © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions 2 8 -2. 0 -3. 0 9. 0 3 4 page 15

Character Data Type Java allows you to process characters using the character data type, char – char represents a single character – a character literal is enclosed in single quotation marks Examples: – char letter = ‘A’; Assigns the character A to the char variable letter – char num. Char = ‘ 4’; Assigns the digit character 4 to the char variable num. Char © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 16

Unicode and ASCII code Computers use binary numbers internally – a character is stored in a computer as a sequence of 0 s and 1 s – Mapping a character to its binary representation is called encoding – There are different ways to encode a character – Java uses Unicode is an encoding scheme Originally designed for 16 -bit character encoding This allowed for 216 = 65, 536 characters © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 17

Unicode and ASCII code Unicode – So Unicode originally allowed only 65, 536 characters – Is that enough characters to represent all the characters in the world? The answer is no. – So Unicode has been extended to allow 1, 112, 064 different types of characters These are called supplementary characters We will not discuss those characters in CPCS-202 – For simplicity, we consider only the original 16 -bit Unicode characters (stored in a char variable) © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 18

Unicode and ASCII code Unicode – Again, we only consider 16 -bit Unicode characters Remember: one byte is eight bits So a 16 -bit Unicode requires two bytes, preceded by u – Also, because reading 16 bits is cumbersome and difficult, Unicode is usually expressed in hexadecimal Remember: – Decimal number system: 10 digits from 0 to 9 – Hexadecimal number system: 16 digits from 0 to F • 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F – We need 4 bits to represent a Hex digit • Example: 15 in decimal is 1111 in binary and F in Hex © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 19

Unicode and ASCII code Unicode – Hex system: © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 20

Unicode and ASCII code Unicode – Unicode is usually expressed in Hexadecimal 16 bits in Unicode Each hexadecimal requires 4 bits So that means each Unicode is expressed in 4 Hex digits! From u 0000 to u. FFFF – Example: © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 21

Unicode and ASCII code ASCII – Most computers use ASCII American Standard Code for International Exchange – 8 -bit encoding scheme Used to represent all uppercase and lowercase letters, all digits, all punctuation marks, and control characters 128 characters total – Unicode includes ASCII code u 0000 to u 007 F representing the 128 ASCII characters © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 22

Unicode and ASCII code ASCII – You can use both ASCII and Unicode in your program – The following statements are equivalent: char letter = ‘A’; char letter = ‘u 0041’; // A’s Unicode value is 0041 – Both statements assign character A to the char variable letter © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 23

Escape Sequences for Special Characters What if you want to print a message with quotation marks printed in the output. – Can you do this: System. out. println("He said "Java is fun""); – Answer: No! This statement will give a compile error. The compiler will see the quotation before the word Java. And the compiler will assume this is the END of the string! So it gets confused when it sees more characters after – How do we overcome this problem? Escape Sequences © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 24

Escape Sequences for Special Characters Escape Sequences: – Java uses a special notation to represent special characters This notation is called an escape sequence Example escape sequences are shown in the table below: © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 25

Escape Sequences for Special Characters Escape Sequences: – So we use a backslash () followed by a character or a combination of digits – Example: System. out. println("He said " Java is fun""); – The output is: He said "Java is fun" – Note that the symbols and " together represent one character © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 26

Escape Sequences for Special Characters Escape Sequences: – So what if you wanted to actually print a backslash – Example: what if you wanted to print the following: t is a tab character So we actually want to print the backslash to the screen – How can you do this? Backslash is an escape character Using a backslash signals to the compiler that a special character should be printed So how do we actually print the backslash: we escape it! System. out. println("\t is a tab character"); © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 27

Casting between char and Numeric Types Implicit casting: – Implicit casting can be used if the result of casting fits into the target variable. – Otherwise, explicit casting is required – Example: Unicode of 'a' is 97 This is within the range of a byte (and of course an int) So the following are okay: byte b = 'a'; int i = 'a'; char c = 97; © Dr. Jonathan Cazalas // same as byte b = (byte)'a'; // same as int i = (int)'a'; // same as char c = (char)97; Chapter 4: Characters, Strings, and Mathematical Functions page 28

Casting between char and Numeric Types Explicit casting: – The following would be incorrect: byte b = 'u. FFF 4'; Why? Because the right side is 16 bits. A byte is 8 bits Clearly, 16 bits does not fit into 8 bits – To force the assignment, use explicit casting: byte b = (byte)'u. FFF 4'; – Remember: a char uses two bytes So any positive integer between 0000 and FFFF in hexadecimal can be cast into a char implicitly. © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 29

Casting between char and Numeric Types Numeric operators – All numeric operators can be applied to char operands – A char operand is automatically cast into a number if the other operand is a number or a character – But if the other operand is a string, the character is concatenated with the string © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 30

Casting between char and Numeric Types Numeric operators – Examples: int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51 System. out. println("i is " + i); // i is 101 int j = 2 + 'a'; // (int)'a' is 97 System. out. println("j is " + j); // j is 99 System. out. println("Chapter " + '2'); System. out. println(j + " is the Unicode for character " + (char)j); Output: i is 101 j is 99 Chapter 2 99 is the Unicode for character c © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 31

Comparing and Testing Characters Two characters can be compared using relational operators – just like comparing two numbers This is done by comparing the Unicode values Examples: 'a' < 'b' is true because the Unicode for 'a' (97) is less than the Unicode for 'b' (98). 'a' < 'A' is false because the Unicode for 'a' (97) is greater than the Unicode for 'A' (65). '1' < '8' is true because the Unicode for '1' (49) is less than the Unicode for '8' (56). © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 32

Comparing and Testing Characters Often you must test whether a character is a number, a letter, or even if it is uppercase or lowercase. – The following code tests whether a character ch is an uppercase letter, a lowercase letter, or a digit: if (ch >= 'A' && ch <= 'Z') System. out. println(ch + " else if (ch >= 'a' && ch <= System. out. println(ch + " else if (ch >= '0' && ch <= System. out. println(ch + " © Dr. Jonathan Cazalas is an uppercase letter"); 'z') is a lowercase letter"); '9') is a numeric character"); Chapter 4: Characters, Strings, and Mathematical Functions page 33

Methods in the Character Class Testing characters is common – Therefore, Java gives the following methods inside the Character class © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 34

Methods in the Character Class Using the Character class: – Examples: System. out. println("is. Digit('a') is " + Character. is. Digit('a')); System. out. println("is. Letter('a') is " + Character. is. Letter('a')); System. out. println("is. Lower. Case('a') is " + Character. is. Lower. Case('a')); System. out. println("is. Upper. Case('a') is " + Character. is. Upper. Case('a')); System. out. println("to. Lower. Case('T') is " + Character. to. Lower. Case('T')); System. out. println("to. Upper. Case('q') is " + Character. to. Upper. Case('q')); Output: is. Digit('a') is false is. Letter('a') is true is. Lower. Case('a') is true is. Upper. Case('a') is false to. Lower. Case('T') is t to. Upper. Case('q') is Q © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 35

Evaluate the following : System. out. println('a' < 'b'); <= 'A'); > 'b'); >= 'A'); System. out. println('a' == 'a'); System. out. println('a' != 'b'); © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions true false true page 36

What is the output of the following program: public class Test { public static void main(String[] args) { char x = 'a'; char y = 'c'; System. out. println(++x); System. out. println(y++); System. out. println(x - y); } } Output: b c -2 © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 37

Write code that generates a random lowercase letter. – Remember: lowercase letters are 97 to 122 in decimal So 26 possible values (letters) public class Random. Lowercase{ public static void main(String[] args) { int x = 97 + (int)(Math. random() * 26); char random. Char = x; System. out. println("Random char: " + random. Char); } } © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 38

The String Type A char represents one character So how do we represent a sequence (a string) of characters? Use the data type called String Example: – The following code declares variable message to be a string with the value "Welcome to Java" String message = "Welcome to Java"; © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 39

The String Type String details: – String is a predefined class in the Java library Just like the classes System and Scanner – The String type is not a primitive type – It is known as a reference type – And the variable declared by a reference type is known as a reference variable that references an object String message = "Welcome to Java"; Here, message is a reference variable that references a string object with the contents "Welcome to Java" © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 40

The String Type String details: – Declaring a String variable: String first. Name; – Assign a value to the String variable: first. Name = "Muhammad Alzahrani"; – Most important: How to use the methods in the String class The following page shows some of the common methods that can be used to operate on Strings © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 41

Simple Methods for String Objects String details: – Strings are objects in Java For this reason, these methods are called "instance methods" – A non-instance method is called a static method All methods in the Math class are static methods – They are not tied to a specific object instance © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 42

Simple Methods for String Objects String details: – Again, string methods are instance methods This means that they are tied to a specific object/string – Therefore, you must invoke them from a specific object/string – Syntax: reference. Variable. method. Name(arguments) Recall: syntax to invoke a static method: – Class. Name. method. Name(arguments) – Example: Math. pow(2, 3); // result is 8 So instead of mentioning the Class of the method We mention the specific variable © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 43

Simple Methods for String Objects Getting String Length – Use the length() method to return the number of characters in a string – Example: String message = "Welcome to Java"; System. out. println("The length of " + message + " is " + message. length()); Output: The length of Welcome to Java is 15 © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 44

Simple Methods for String Objects Getting Characters from a String – The s. char. At(index) method can be used to retrieve a specific character in a string s The index is between 0 and s. length()-1 Example: message. char. At(0); © Dr. Jonathan Cazalas // Returns the character W Chapter 4: Characters, Strings, and Mathematical Functions page 45

Simple Methods for String Objects Concatenating Strings – You can use the concat method to concatenate two strings – Example: Strings s 3 = s 1. concat(s 2); concatenates s 1 and s 2 into s 3 – String concatenation is very common in Java – Therefore, Java gives is the plus (+) operator for this – Example: String s 3 = s 1 + s 2; © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 46

Simple Methods for String Objects Concatenating Strings – Remember: you can concatenate a number with a string – At least one of the operands must be a string – Examples: String message = "Welcome " + "to " + "Java"; String s = "Chapter " + 2; – s becomes "Chapter 2" String s 1 = "Supplement " + 'B'; – s 1 becomes "Supplement B" © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 47

Simple Methods for String Objects Concatenating Strings – The augmented += operator can also be used for concatenation with strings – Example: String message = "Welcome to Java"; message += ", and Java is fun. "; System. out. println(message); Output: "Welcome to Java, and Java is fun. " © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 48

Simple Methods for String Objects Concatenating Strings – Final example: If i=1 and j=2, what is the output of the following: System. out. println("i + j is " + i + j); Output: "i + j is 12" Why? – – In Java, we read from left to right So we have the String "i + j is " concatenated with the int i The result: a new String ("i + j is 1") This new String is the concatenated with the int j – You can force addition by enclosing the i + j in parentheses © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 49

Simple Methods for String Objects Converting Strings – Methods: to. Lower. Case() method returns a new string with all lowercase letters to. Upper. Case() method returns a new string with all uppercase letters trim() method returns a new string after removing all whitespace characters from both ends of the string – Final example: "Welcome". to. Lower. Case(); // returns a new string welcome "Welcome". to. Upper. Case(); // returns a new string WELCOME "t a b c ". trim(); // returns a new string a b c © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 50

Reading a String from the Console How to read a string from the console – Use the next() method on a Scanner object System. out. print("Enter three words separated by spaces: "); String s 1 = input. next(); // assume we made Scanner object String s 2 = input. next(); String s 3 = input. next(); System. out. println("s 1 is " + s 1); System. out. println("s 2 is " + s 2); System. out. println("s 3 is " + s 3); © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 51

Reading a String from the Console How to read a complete line from the console – Use the next. Line() method on a Scanner object Scanner input = new Scanner(System. in); System. out. println("Enter a line: "); String s = input. next. Line(); System. out. println("The line entered is " + s); © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 52

Reading a Character from the Console How to read a single character from the console – Use the next. Line() method to read a string and then invoke the char. At(0) method on the string Scanner input = new Scanner(System. in); System. out. print("Enter a character: "); String s = input. next. Line(); char ch = s. char. At(0); System. out. println("The character entered is " + ch); © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 53

Comparing Strings The String class has many methods you can use to compare two strings. © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 54

Comparing Strings String equality – How can you check if two strings are equal? – Note: you cannot use the == operator – Example: if (s 1 == s 2) System. out. println("s 1 and s 2 are the same object"); else System. out. println("s 1 and s 2 are different object"); This will only tell us if two string reference variables point to (refer to) the same object © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 55

Comparing Strings String equality – So how can you check if two strings are equal? – Meaning, how to check if they have same contents? – Use the equals() method – Example: if (s 1. equals(s 2)) System. out. println("s 1 and s 2 have same contents"); else System. out. println("s 1 and s 2 are not equal"); © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 56

Comparing Strings String equality – Example: String s 1 = "Welcome to Java"; String s 2 = "Welcome to Java"; String s 3 = "Welcome to C++"; System. out. println(s 1. equals(s 2)); // true System. out. println(s 1. equals(s 3)); // false © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 57

Comparing Strings compare. To() method – We can use the compare. To() method to compare two strings This allows us to alphabetically order the strings – Syntax: s 1. compare. To(s 2); Returns the value 0 if s 1 is equal to s 2 Returns a value less than 0 if s 1 is "less than" s 2 Returns a value greater than 0 if s 1 is "greater than" s 2 – Example: "abc". compare. To("abg"); © Dr. Jonathan Cazalas // returns -4 Chapter 4: Characters, Strings, and Mathematical Functions page 58

Program 1: Order. Two. Cities Write a program that prompts the user to enter two cities and then displays them in alphabetical order. Remember: – Step 1: Problem-solving Phase – Step 2: Implementation Phase © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 59

Program 1: Order. Two. Cities Step 1: Problem-solving Phase – Algorithm: 2. Prompt the user to enter an two Strings Compare the two strings using compare. To() method 3. Print the cities in correct alphabetical order 1. © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 60

Program 1: Order. Two. Cities Step 2: Implementation © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 61

Program 1: Order. Two. Cities Run the Program: – Note: Some city names have multiple words – Such as New York Therefore, we used next. Line() to scan the city name – Instead of next() Click here to view and trace code © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 62

Obtaining Substrings You can get a substring, from a string, by using the substring method in the String class Example: String message = "Welcome to Java"; String message = message. substring(0, 11) + "HTML"; System. out. println(message); – Output: Welcome to HTML © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 63

Obtaining Substrings Java gives you two substring methods: – substring(begin. Index) Returns this string's substring that begins with the character at the specified begin. Index and extends to the end of the string – substring(begin. Index, end. Index) Returns this string's substring that begins with the character at the specified begin. Index and extends to the character at index end. Index– 1 – NOTE: the character at end. Index is NOT part of the substring © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 64

Finding a Character or a Substring in a String The String class provides several versions of index. Of and last. Index. Of methods to find a character or a substring in a string © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 65

Finding a Character or a Substring in a String The String class provides several versions of index. Of and last. Index. Of methods to find a character or a substring in a string – Examples: "Welcome "Welcome © Dr. Jonathan Cazalas to to to Java". index. Of('W') returns 0. Java". index. Of('o') returns 4. Java". index. Of('o', 5) returns 9. Java". index. Of("come") returns 3. Java". index. Of("Java", 5) returns 11. Java". index. Of("java", 5) returns -1. Chapter 4: Characters, Strings, and Mathematical Functions page 66

Finding a Character or a Substring in a String The String class provides several versions of index. Of and last. Index. Of methods to find a character or a substring in a string – Examples: "Welcome "Welcome © Dr. Jonathan Cazalas to to to Java". last. Index. Of('W') returns 0. Java". last. Index. Of('o') returns 9. Java". last. Index. Of('o', 5) returns 4. Java". last. Index. Of("come") returns 3. Java". last. Index. Of("Java", 5) returns -1. Java". last. Index. Of("Java") returns 11. Chapter 4: Characters, Strings, and Mathematical Functions page 67

Finding a Character or a Substring in a String Practical Example – Suppose a string s contains the first name and last name of a student, separated by a space – How can you extract the first name and last name? – Can we use a method to find the space? YES! We can use the index. Of(' ') – This will give us the index of the first space Then, because we know this index, we can use the substring() method to find the first name and the last name © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 68

Finding a Character or a Substring in a String Practical Example – Solution: String s = "Kim Jones"; int k = s. index. Of(' '); String first. Name = s. substring(0, k); String last. Name = s. substring(k + 1); © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 69

Conversion between Strings and Numbers You can convert a numeric string into an int How? – Use the Integer. parse. Int() method – Example: int value = Integer. parse. Int("152"); You can also convert a string to a double – Use the Double. parse. Double() method – Example: double value = Double. parse. Double("827. 55"); © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 70

Conversion between Strings and Numbers Can you convert a number to a String? – Yes. – You can do it a complicated way We won't bother showing you! – OR, you do it the EASY way: int number = 7; String s = number + ""; kinda like a "hack" But it works great! We concatenate a number with the empty string Result: we get a string representation of the number! © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 71

Suppose that s 1, s 2, and s 3 are three strings: String s 1 = "Welcome to Java"; String s 2 = "Programming is fun"; String s 3 = "Welcome to Java"; What are the results of the following expressions? a. b. c. d. e. f. g. h. s 1 == s 2 s 1 == s 3 s 1. equals(s 2) s 1. equals(s 3) s 1. compare. To(s 2) s 2. compare. To(s 3) s 2. compare. To(s 2) s 1. char. At(0) © Dr. Jonathan Cazalas false true Greater than 0 Less than 0 0 (cause contents are equal) W Chapter 4: Characters, Strings, and Mathematical Functions page 72

Suppose that s 1, s 2, and s 3 are three strings: String s 1 = "Welcome to Java"; String s 2 = "Programming is fun"; String s 3 = "Welcome to Java"; What are the results of the following expressions? a. b. c. d. e. f. g. h. s 1. index. Of('J') s 1. index. Of('j') s 1. index. Of("to") s 1. last. Index. Of('a') s 1. length() s 1. substring(5, 12) s 1. ends. With("Java") © Dr. Jonathan Cazalas 11 -1 (meaning, not found) 8 (the starting index of "to") 14 15 me to Java me to J true Chapter 4: Characters, Strings, and Mathematical Functions page 73

Show the output of the following expressions: a) b) c) d) e) System. out. println("1" System. out. println('1' © Dr. Jonathan Cazalas + + + 1); 1 + 1); (1 + 1)); 1 + 1); Chapter 4: Characters, Strings, and Mathematical Functions 11 50 111 12 51 page 74

Program 2: Hex. Digit 2 Dec Write a program that prompts the user to enter one hex digit and then displays this as a decimal value. Remember: – Step 1: Problem-solving Phase – Step 2: Implementation Phase © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 75

Program 2: Hex. Digit 2 Dec Step 1: Problem-solving Phase – Algorithm: 1. 2. 3. Prompt the user to enter a hex digit Check to see if the input is exactly one digit If so, confirm the input is between 0 -9 or A-F – Then print the decimal equivalent 4. Otherwise, print invalid input – For step 3 above, we can use methods we've learned in this Chapter © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 76

Program 2: Hex. Digit 2 Dec Step 2: Implementation © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 77

Program 2: Hex. Digit 2 Dec Step 2: Implementation is A-F? is 0 -9? © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 78

Program 2: Hex. Digit 2 Dec Run the Program: Click here to view and trace code © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 79

Program 3: Lottery Re-do the Lottery program from Chapter 3. This time, use strings for both the randomly generated number and the user input. The logic is easier than dealing with mod! Remember: – Step 1: Problem-solving Phase – Step 2: Implementation Phase © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 80

Program 3: Lottery Step 1: Problem-solving Phase – Notes: The user will win money according to the following rules: 1. 2. 3. If the user lottery number matches the winning lottery number in the exact order, the award is $10, 000 If all digits in the user lottery number match all digits in the winning lottery number (but not in the exact order), the award is $3, 000 If only one digit in the user lottery number matches the winning lottery number, the award is $1, 000 User MUST enter two digits © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 81

Program 3: Lottery Step 1: Problem-solving Phase – Algorithm: 1. Randomly generate a winning lottery number – 2. 3. 4. 5. Save that number as a String! Prompt user for input Scan the lottery number from user as a String! Compare user number with winning number, and determine winning amount (if any) 6. © Dr. Jonathan Cazalas Between 0 and 99. This is easy. int lottery = (int)(Math. random() * 100); Here we must compare the actual digits!!! Display results to user Chapter 4: Characters, Strings, and Mathematical Functions page 82

Program 3: Lottery Step 1: Problem-solving Phase – So how do we compare digits? We are saving these two-digit numbers as strings Therefore, we can extract the individual digits using the String method char. At() This is MUCH easier than mod! Example: String number = "49"; char c 1 = number. char. At(0); char c 2 = number. char. At(1); © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 83

Program 3: Lottery Step 2: Implementation © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 84

Program 3: Lottery Step 2: Implementation © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 85

Program 3: Lottery Run the Program: Click here to view and trace code © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 86

Formatting Output You can use the System. out. printf method to display formatted output – When printing double values, often we do not need or want all the decimals. – In fact, often we want only two (for money)! – In Chapter 2, we learned that you can get two digits after the decimal as follows: double x = 16. 404674; x = (int)(x * 100) / 100. 0; However, if we print x, we will get 16. 4 – The final zero will not print! So how do we print the zero? © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 87

Formatting Output You can use the System. out. printf method to display formatted output – How to print 16. 404674 with only two decimals? – Easy! double x = 16. 404674; System. out. printf("x is %4. 2 f", x); Output: x is 16. 40 © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 88

Formatting Output You can use the System. out. printf method to display formatted output – Another example: © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 89

Formatting Output You can use the System. out. printf method to display formatted output – Common format specifiers: © Dr. Jonathan Cazalas Chapter 4: Characters, Strings, and Mathematical Functions page 90
- Slides: 90