Percent of total grade-50 Directions: SHOW ALL YOUR WORK. REMEM THAT PROGRAMSEGM
ID: 3820532 • Letter: P
Question
Percent of total grade-50 Directions: SHOW ALL YOUR WORK. REMEM THAT PROGRAMSEGMENTS ARE TO BE BER WRITTEN IN JAVA. Notes: Assume that the classes listed in the Quick Reference found in the Appendix have been imported where appropriate. Unless otherwise noted in the question, assume that parameters in method calls are not null and that methods are called only when their preconditions are satisfied. In writing solutions for each question, you may use any of the accessible methods that are listed in classes defined in that question. Writing significant amounts of code that can be replaced by a call to one of these methods may not receive full credit. 1. Consider the following partial declaration for a wordscrambler class. The constructor for the wordscrambler class takes an even-length array of string objects and initializes the instance variable scrambled Words public class Wordscrambler private String scrambledWords eparam wordArr an amay of String objects Precondition: wordArr. length is even public wordscrambler (String wordArr) scrambledWords a mixedWords (wordArr): eparam word1 a string of characters @param word2 a String of characters ereturn a string that contains the first half of word1 and the second half of word2 private string recombine (String word1, String word2) to be implemented in part (a) eparam words an array of String objects Precondition: words.length is even ereturn an array of string objects created by recombining pairs of strings in array words Postcondition: the length of the returmed array is words length. private string mixedwords (string words) to be implemented in part (b) There may be instance variables, constructors, and methods that are not shown. GO ON TO THE NEXT PAGE. -42-Explanation / Answer
CODE:
package temp;
public class WordScrambler{
private String[] scrambledWords;
public WordScrambler(String[] wordArr){
scrambledWords = mixedWords(wordArr);
}
private String recombine(String word1, String word2){
return word1.substring(0,word1.length()/2) + word2.substring(word2.length()/2,word2.length());
}
private String[] mixedWords(String[] words){
String[] mixed = new String[words.length];
for (int i=0; i<words.length; i+=2) {
mixed[i] = recombine(words[i], words[i+1]);
mixed[i+1] = recombine(words[i+1], words[i]);
}
return mixed;
}
public String[] scrambledWords(){
return scrambledWords;
}
public static void main(String[] args) {
String[] wow = {"apple", "pear", "this", "cat"};
WordScrambler w = new WordScrambler(wow);
wow = w.scrambledWords();
for (int i=0; i<wow.length; i++) {
System.out.println(wow[i]);
}
}
}
OUTPUT:
apar
peple
that
cis
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.