Java Reference
In-Depth Information
(o) Assign the index of the first occurrence of the character e in s1 to an int
variable x .
(p) Assign the index of the last occurrence of the string abc in s1 to an int
variable   x .
4.5 Case Studies
Strings are fundamental in programming. The ability to write programs using strings
is essential in learning Java programming.
Key
Point
You will frequently use strings to write useful programs. This section presents three examples
of solving problems using strings.
4.5.1 Case Study: Guessing Birthdays
You can find out the date of the month when your friend was born by asking five questions.
Each question asks whether the day is in one of the five sets of numbers.
= 19
+
357
9111315
17
1
2367
10
4
567
8
91011
16
17
18
19
11
14
15
12
13
14
15
12
13
14
15
20
21
22
23
19
21
23
18
19
22
23
20
21
22
23
24
25
26
27
24
25
26
27
25
27
29
31
26
27
30
31
28
29
30
31
28
29
30
31
28
29
30
31
Set1
Set2
Set3
Set4
Set5
The birthday is the sum of the first numbers in the sets where the day appears. For example,
if the birthday is 19 , it appears in Set1, Set2, and Set5. The first numbers in these three sets
are 1 , 2 , and 16 . Their sum is 19 .
Listing  4.3 gives a program that prompts the user to answer whether the day is in Set1
(lines 41-44), in Set2 (lines 50-53), in Set3 (lines 59-62), in Set4 (lines 68-71), and in Set5
(lines 77-80). If the number is in the set, the program adds the first number in the set to day
(lines 47, 56, 65, 74, 83).
L ISTING 4.3
GuessBirthday.java
1 import java.util.Scanner;
2
3 public class GuessBirthday {
4 public static void main(String[] args) {
5 String set1 =
6
" 1 3 5 7\n" +
7
" 9 11 13 15\n" +
8
"17 19 21 23\n" +
9
"25 27 29 31" ;
10
11 String set2 =
12
" 2 3 6 7\n" +
 
 
 
Search WWH ::




Custom Search