Complete the implementation of the (static) class method Stringll fndAndReplace(
ID: 3787022 • Letter: C
Question
Complete the implementation of the (static) class method Stringll fndAndReplace(Stringll in, Stringll what, Stringllwith) of th class Utils. The method returns acopy of the arrayin where each word occurring in the array what has e been replaced by the word occurring at the corresponding position in the array with. The array designated by n must remain unchanged. Later in the semester, we will learn about exceptions. Exceptions provide tools forhandling error situations. In the meantime, the methodfindAndReplace returns null whenever one of the preconditions of the methods is violated: In particular, the formal parameters cannot be null. For all three arrays, none of the element can be nul The query and replacement arrays must be off thesame length.Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
public class Utils {
public static String[] findAndReplace(String[] in, String[] what, String[] with){
// base case : Precondition
if(in == null || what == null || with == null)
return null;
if(what.length != with.length)
return null;
// creating a new String array of same length
String[] out = new String[in.length];
// traversing 'in' array
for(int i=0; i<in.length; i++){
// current element of 'in' array
String str = in[i];
// if current element of in is null then return null
if(str == null)
return null;
// finding whether 'str' is in 'what' array or not
int j = 0;
while(j< what.length){
// if current entry of with or what uis null then return null
if(what[j] == null || with[j] == null)
return null;
if(str.equals(what[j]))
break;
j++;
}
// if 'str' is in 'what' array then replace 'str' with corresponding value
// of 'with' array while storing in 'out' array
if(j != what.length)
out[i] = with[j];
else // did not find in what array
out[i] = in[i];
}
return out;
}
}