Answer:Here's how the program works:
It asks the user to enter a sentence, a word to replace, and a replacement word, using the Scanner class.
It uses the String method replace() to find and replace the first word with the second word in the sentence.
If the word was found and replaced, it outputs the new sentence. Otherwise, it outputs an error message.
Note that the replace() method replaces all occurrences of the first word in the sentence. If you want to replace only the first occurrence, you can use the replaceFirst() method instead.
Step-by-step explanation:
import java.util.Scanner;
public class WordSubstitution {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Ask user for input
System.out.print("Enter a sentence: ");
String sentence = input.nextLine();
System.out.print("Enter a word to replace: ");
String word1 = input.next();
System.out.print("Enter a replacement word: ");
String word2 = input.next();
// Find and replace the word
String newSentence = sentence.replace(word1, word2);
// Check if the word was found and replaced
if (newSentence.equals(sentence)) {
System.out.println("Error: the word '" + word1 + "' was not found in the sentence.");
} else {
System.out.println("The new sentence is: " + newSentence);
}
input.close();
}
}