Chapter 4: Tracing 101-2

Classwork:

Use paper and pencil/pen to trace this code snippets and show how each of the choices fail except one:

Lazy student spoiler: DO NOT USE THE COMPUTER

a.
One of the rules for converting English to Pig Latin states: If a word begins with a
consonant, move the consonant to the end of the word and add “ay”. Thus “dog”
becomes “ogday”, and “crisp” becomes “rispcay”. Suppose s is a String
containing an English word that begins with a consonant. Which of the following
creates the correct corresponding word in Pig Latin? Assume the declarations

String ayString =”ay”;
String pigString;
pigString = s.substring(0,s.length()) + s.substring(0,1) + ayString;
pigString = s.substring(1,s.length()) + s.substring(0,0) + ayString;
pigString = s.substring(0,s.length()-1) + s.substring(0,1) + ayString;
pigString = s.substring(1,s.length()-1) + s.substring(0,0) + ayString;
pigString = s.substring(1,s.length()) + s.substring(0,1) + ayString; 

b.
This question refers to the getString method shown below:

public static String getString(String s1, String s2)
{
    int index = s1.indexOf(s2); // it returns the index of s2
    return s1.subtring(index, index + s2.length());
}

Which is true about getString? It may return a string that
I Is equal to s2.
II Has no characters in common with s2.
III Is equal to s1.

c.

public static String doSomething(String s)
{
    Final String BLANK = " ";            //BLANK contains a single space
    String str = "";                     // empty String
    String temp;
    for (int i = 0; i < s.length(); i++)
    {
        temp =s.substring(i, i + 1);
        if ( !(temp.equals(BLANK)))
             str += temp;
    }
    return str;
}

Shows how each doesn’t work except the right one:
It returns s unchanged.
It returns s with all its blanks removed.
It returns a String that is equivalent to s with all its blanks removed.
It returns a String that is an exact copy of s.
It returns a String that contains s.length() of blanks.

NOTE: Do the work even if you got the questions right.

Ch2TestSolTracing.pdf
Printer-friendly version

I will collect your work at the end of the period.