Quiz Review - Additional Questions
True or False
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";
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
Quick Code
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;
}