Quiz Review - Additional Questions

True or False

  1. if a="Andrew Wiles proved Fermat's Last Theorem", a.substring(1,6) would equal "Andrew".
  2. if a="HI", a.toLowerCase() would equal "hi"
  3. if a='g', then a++ would equal 'h';
  4. if a='g', then a+=2 would equal 'i';
  5. you can print out a char array directly (without a loop) in System.out.println.
  6. concatenation is the process of mushing two strings together to make one string.
  7. String Tokenizer is found in the io class.
  8. if a = "bob's your uncle" then a.length tells us how long the string is (16 characters)
  9. Alan Turing was the first to use frequency analysis to break codes.
  10. The only unbroken American code in WWII was the Navajo code.

Quick Code

Suppose you have:

String a = "We all love computer class";
String b = "It is so much fun";
String c = "We love strings too";

  1. Print out "We all love computer class. It is so much fun." (Note punctuation)
  2. Change all of the 'o's in String c to 'z'.
  3. Change b to lower case.
  4. Print out the first two letters of String b.
  5. Print out the character in position 6 in String c.

Methods

Write the following methods:

//Question 1 - checks if the word contains the letter
public boolean contains (String word, char letter)

//Question 2 - takes a string and removes all spaces
public static String removeSpaces (String word)

//Question 3 - takes a string that is a sentence and returns
//    the average length of all the words in the sentence
public static int avgWordLen (String word)


Answers

True or False

  1. F, A is in position 0. All arrays start at 0. Always.
  2. T.
  3. T.
  4. F. You can only do ++, +=2 makes java upset.
  5. T.
  6. T.
  7. F. In java.util.StringTokenizer
  8. F. a.length() does. Note the brackets.
  9. F. al-Kindi was.
  10. T.

Quick Code

  1. System.out.println(a + ". "+b+".");
  2. c=c.replace('o', 'z');
  3. b=b.toLowerCase();
  4. System.out.println(b.substring(0,2));
  5. System.out.println(c.charAt(6));

Methods

1. //checks if the word contains the letter
public boolean contains ( String word, char letter)
{
for (int i = 0 ; i < word.length () ; i++)
{
if (word.charAt (i) == letter)

return true;

}
return false;
}

//2 removes all spaces
public static String removeSpaces (String word)
{
String newie = "";
for (int i = 0 ; i < word.length () ; i++)
{
if (word.charAt (i) != ' ')
newie += word.charAt (i);
}
return newie;
}

//3 returns avg word length
public static int avgWordLen (String word)
{
StringTokenizer tokenizer = new StringTokenizer (word);
int numberOfWords = tokenizer.countTokens ();
int totalLen = 0;
//loop for number of words in description
for (int i = 0 ; i < numberOfWords ; i++)
{
String nextword = tokenizer.nextToken (); //peel off next word
totalLen += nextword.length ();
}
return totalLen / numberOfWords;

}