Question: This code is supposed to replace GREEN EGGS AND HAM, GREEN EGGS AND PIZZA, I DO NOT LIKE GREEN EGGS AND HAM with GREEN EGGS

This code is supposed to replace GREEN EGGS AND HAM, GREEN EGGS AND PIZZA, I DO NOT LIKE GREEN EGGS AND HAM with GREEN EGGS AND HAM, GREEN EGGS AND PIZZA, I DO NOT LIKE GREEN EGGS AND Pizza but some reason when it runs nothing happens to the last phrase and remains untouched. Is there a reason for this?

Method Code:

public int findNthOccurrence(String str, int n)

{

int count = 0;

for(int i = 0; i < currentSentence.length() - str.length(); i++) {

for(int j = 0; j < str.length(); j++) {

if(str.charAt(j) != currentSentence.charAt(i + j)) {

break;

}

if(j == str.length() - 1) {

count++;

}

}

if (count == n) {

return i;

}

}

return -1;

}

/** Modifies currentSentence by replacing the nth occurrence of str with repl.

* If the nth occurrence does not exist, currentSentence is unchanged.

* Precondition: str.length() > 0 and n > 0

*/

public void replaceNthOccurrence(String str, int n, String repl)

{

int outcome = findNthOccurrence(str,n);

if(outcome < 0) {

return;

}

currentSentence = currentSentence.substring(0, outcome) + repl + currentSentence.substring(outcome + str.length());

}

Client Code:

s2.replaceNthOccurrence("HAM",2,"PIZZA");

System.out.println("replaceNthOccurrence(HAM,2,PIZZA)");

System.out.println("Sentence 2: "+ s2);

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!