Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a java program that replaces certain words and phrases in a sentence with

ID: 3723932 • Letter: W

Question

Write a java program that replaces certain words and phrases in a sentence with other words and phrases:

Rules of replacement:

1.

Replace "moron" with "unwise person"

Replace "idiot" with "silly"

Replace "stupid" with "unwise"

Replace "stupidly" with "unwisely"

Replace "ugly" with "uniquely beautiful"

Replace "fake" with "innovative

2. Unwise unwise - If someone inputs "stupid moron" in a phrase, the replacement should be "unwise person" instead of "unwise unwise person"

3. Prior word adjustments - If someone inputs "He's such a moron!", the replacement should be "He's such an unwise person!"

Explanation / Answer

Hi... I have written java program for the above.

ReplaceStrings.java

import java.util.Scanner;

public class ReplaceStrings {

public static void main(String[] args) {

// TODO Auto-generated method stub

/*Replace "moron" with "unwise person"

Replace "idiot" with "silly"

Replace "stupid" with "unwise"

Replace "stupidly" with "unwisely"

Replace "ugly" with "uniquely beautiful"

Replace "fake" with "innovative

*/ String find[] = {"moron","idiot","stupid","stupidly","ugly","fake"};

String replace[] = {"unwise person","silly","unwise","unwisely","uniquely beautiful","innovative"};

Scanner sc = new Scanner(System.in);

System.out.print("Enter String:");

String val = sc.nextLine();

String original = val;

for(int i=0;i<find.length;i++){

val = val.replace(find[i], replace[i]);

}

//System.out.println(val);

String check[] = val.split(" ");

String newString="";

boolean fl = false;

for(int i=1;i<check.length;i++){

if(check[i-1]==check[i]){

fl = true;

}else{

if(newString.isEmpty()){

newString = check[i-1];

}else{

newString+=" "+check[i];

}

}

}

if(!fl){

newString = val;

}

//System.out.println(newString);

if(!newString.equalsIgnoreCase(original)){

if(newString.indexOf(" a ")>-1){

newString = newString.replace(" a ", " an ");

}

}

System.out.println("Replaced String:"+newString);

}

}

Output:

Enter String:He's such a moron!
Replaced String:He's such an unwise person!

Please test the code and let me know any issues. Thank you. All the best.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote