Lab 5: Useful String Methods & Recursion

Objectives

The main goals for this lab are:

  1. To get practice with useful String methods.

  2. To practice writing recursive functions.


1. Simple Strings

Now we will look at a few String methods.

If we have a String, we can determine the following information:

Write a program called WordInfo.java where you will ask a user for a word and then a character. The program will then tell the user:

  1. how long the word is

  2. where in the word that character appears. By where we mean is it the 1st letter, the 2nd letter, etc. If the character appears multiple times, you only need to tell the user where the character first appears.

$ javac WordInfo.java
$ java WordInfo
Please give me a word: character
Please give me a character: a
character has 9 letters, a is the #3 letter in the character

TODO: Show Prof. Shiptoski your work before continuing.


2. More Strings

2.1 Even Length

Write a method, isEvenLength, which returns true if the given String has an even number of characters and false otherwise. Implement tests in main to check your answer. For example,


2.2 Substrings

Write a method called subStringN with 2 paramaters, a string and an integer n.

The method should print 2 substrings:

  1. the first n characters of the string

  2. the last n characters of the string.

Examples:

If the length of the string is shorter than N, print a message telling the user.


3. Recursion

3.1 Sum of Numbers

Given a String of numbers, write a method called sum that returns the sum of all the numbers in the String. sum should have one parameter, the string of numbers.

For example sum("1234") should return 10.

Below we are going to implement this together. The following questions will help guide you.

Question 1: Consider the charAt() function in Java. How could we use this function in our recursive function, to get the digits out of the string?

 
 
 
 
 

Question 2: Let’s now think about our base case, i.e. when we no longer want to make a recursive call. What would be special about the value assigned to this parameter (the String that is passed in to the method) to tell us to stop making a recursive call?

 
 
 
 
 

TODO: Implement the base case in the method.

Question 3: During each recursive step, what do we want to keep track off, and what do we want to punt down the line? HINT: What is the result of 1 + sum("234")?

 
 
 
 
 

Question 4: Given the string "1234", how can we extract the 1?

 
 
 
 
 

Question 5: Given the character '1', how can we get the integer value 1?

 
 
 
 
 

Question 6: Given the String "1234", how can we get the substring "234"? HINT: Think about the substring() method we discussed in class.

 
 
 
 
 

TODO: Implement the recursive step right after your base case.

TODO: In your main method, test sum() by invoking the method with the following arugments:

TODO: Show Prof. Shiptoski your work and then you are all done with lab 5.