Homework Solution

Control Structures

Problems to be Submitted (30 points)

  1. (10 points)

    Assume that the following variable has been initialized:

    String school = "Saint Louis University";
    Predict the return value of each of the following commands:

    1. school.length()
      22

    2. school.charAt(3)
      n

    3. school.indexOf('s')
      10

    4. school.substring(3,8)
      nt Lo

    5. school.substring(15)
      versity

  2. (10 points)

    There is an important difference between the functions split and splitTokens, which we illustrate with the following two examples:

    1. split("multimedia", "im")
      This produces the list ["mult", "edia"]

      The split function uses the second parameter as a string that is used in its entirety as a divider. Note that there is only one occurrence of pattern im in multimedia, leaving two surrounding pieces mult and edia.

    2. splitTokens("multimedia", "im")
      This produces the list ["ult", "ed", "a"]

      The second parameter for the splitTokens function is considered as a set of characters, any one of which results in spliting the string. So in this example, any "i" or "m" or consecutive combination of those is used to divide the string. Thus it is viewed as multimedia leaving three resulting pieces "ult", "ed", and "a".


    Experiment with these two command, determine the result of each, and then explain in your own words why the respective functions split and splitTokens produces such results.

  3. (10 points)

    Assume that the variable birthday is a string that describes a date such as "3/31/15" or "12/9/1906". You cannot assume the number of digits in any part, but you can presume there are precisely two slashes and that if a two digit number is given for the year, that it implictly begins with 20 (i.e., the "15" means "2015").

    Give a code fragment that assumes such a general birthday string and defines three integer variables, month, date, and year with the appropriate values. That is, if the birthday string were "3/31/15" then you should end up with month = 3, date = 31, and year = 2015 but your code must be written a way that works on any such (well-formed) example.

    int[] pieces = int(split(birthday,"/"));
    month = pieces[0];
    date = pieces[1];
    year = pieces[2];
    if (year < 100) {
      year += 2000;          // convert 15 to 2015, for example
    }
    


Last modified: Friday, 24 April 2015