Lab #4: Playing with String Methods

The goal of this lab is to write a class PlayWithScanner that uses a Scanner object to receive input from the user and acts on the input. The program works as follows:

  1. The program creates a Scanner object from the keyboard
  2. The program prompts the user to enter an input String and receives it by way of the nextLine method of the Scanner object. This way the user is permitted to include a whitespae or a tab in the input String.
  3. Using a for-loop the program prints each letter of the input String one character per line along with their position value.
  4. The program creates a String that is the reverse of the input String; that is, the String in which the letters of the input String appear in the reverse order, and prints the reverse on the screen. This String can be created using a for-loop.
  5. The program asks the user to enter a position value and receives it using nextInt and prints on the screen the prefix of the input String ending at the position as well as the suffix of the String starting from that position.
  6. The program executes nextLine of the Scanner to read off the new line.
  7. The program prompts the user to enter a pattern and receives it using the nextLine method and then counts the number of times in which the pattern the user has entered appears in the input String. This can be accomplished by producing all the suffixes of the input String and checking whether they start with the pattern. By using a counter variable and adds 1 to the counter each time the test passes the counter shall be increased. Normally we would use an if-statement in this situation, but this is something we are YET to study. So, we will resort to a mathematical method for converting the return value of the indexOf method to 0/1 as follows:

Here is a sample execution:

% java PlayWithScanner
Enter a String and hit return: Mean Mister Mustard sleeps in the park, shaves in the dark trying to save paper
charAt
0: M
1: e
2: a
3: n
4:
5: M
6: i
7: s
8: t
9: e
10: r
11:
12: M
13: u
14: s
15: t
16: a
17: r
18: d
19:
20: s
21: l
22: e
23: e
24: p
25: s
26:
27: i
28: n
29:
30: t
31: h
32: e
33:
34: p
35: a
36: r
37: k
38: ,
39:
40: s
41: h
42: a
43: v
44: e
45: s
46:
47: i
48: n
49:
50: t
51: h
52: e
53:
54: d
55: a
56: r
57: k
58:
59: t
60: r
61: y
62: i
63: n
64: g
65:
66: t
67: o
68:
69: s
70: a
71: v
72: e
73:
74: p
75: a
76: p
77: e
78: r
The reverse: repap evas ot gniyrt krad eht ni sevahs ,krap eht ni speels dratsuM retsiM naeM
Enter position: 20
The prefix: Mean Mister Mustard
The suffix: sleeps in the park, shaves in the dark trying to save paper
Enter pattern: p
The number of occurrences: 4

You may use the template PlayWithScanner.java in writing your code.

Go back to the lab main page

Go back to the home page