Word Scrambler
<< Bee | APQuestionsTrailIndex | Mountain >>
Starter Code
WordScrambler.java
public class WordScrambler
{
private String[] scrambledWords;
/** @param wordArr an array of String objects
* Precondition: wordArr.length is even
*/
public WordScrambler(String[] wordArr)
{
scrambledWords = mixedWords(wordArr);
}
/** @param word1 a String of characters
* @param word2 a String of characters
* @return a String that contains the first half of word1 and the second half of word2
*/
public String recombine(String word1, String word2)
{ /* to be implemented in part (a) */
}
/** @param words an array of String objects
* Precondition: words.length is even
* @return an array of String objects created by recombining pairs of strings in array words
* Postcondition: the length of the returned array is words.length
*/
public String[] mixedWords(String[] words)
{ /* to be implemented in part (b) */
}
// There may be instance variables, constructors, and methods that are not shown.
}
WordScramblerTester.java
import java.util.ArrayList;
public class WordScramblerTester
{
public static void main(String[] args)
{
String[] words={"apple", "pear", "this", "cat"};
WordScrambler w=new WordScrambler(words);
System.out.println("Testing part (a):the recombine method" );
System.out.println("Should be 'apar': "+w.recombine("apple","pear"));
System.out.println("Should be 'peple': "+w.recombine("pear","apple"));
System.out.println("Testing part (b): the mixedWords method" );
System.out.println("Sould be 'apar', 'peple', 'that', 'cis':");
String[] output=w.mixedWords(words);
for (String s:output) System.out.print(s+" ");
}
}
Solutions
part(a)
private String recombine(String word1, String word2)
{
word1=word1.subString(0,(word1.length()/2)+1);
word2=word2.subString(word2.length()/2,word2.length());
String word3= word1.concat(word2);
return word3;
}
or
public String recombine(String word1, String word2)
{ return word1.substring(0,word1.length()/2)+word2.substring(word2.length()/2);}
part(b)
public String[] mixedWords(String[] words)
{ String charlie [] = new String[words.length];
for(int w = 0; w<=words.length-2; w+=2){
String buffer1 =words[w];
String buffer2 =words[w+1];
charlie[w]=recombine(buffer1,buffer2);
charlie[w+1]=recombine(buffer2,buffer1);
}
return charlie;
}
