Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

From Herds To Insights Harnessing Data Analytics For Sustainable Livestock Farming

Authors: Prof Suresh Neethirajan

1st Edition

B0CFD6K6KK, 979-8857075487

More Books

Students also viewed these Databases questions

Question

Discuss all branches of science

Answered: 1 week ago