Challenge: Write a Java program that asks the user to enter a phrase with a word repeated 3 times in it and three different words to use as a replacement. An example of the program output:
Solution:
import java.util.*;
class lab3_2{
public static void main (String[]args)
{
String phrase;
String wordRepeated;
String a,b,c;
Scanner in=new Scanner(System.in);
System.out.println("Enter a phrase with 3 words in it repeated: ");
phrase=in.nextLine();
System.out.println("Enter the word that is repeated: ");
wordRepeated=in.nextLine();
System.out.println("Enter the replacement for the first occurrence: ");
a=in.nextLine();
System.out.println("Enter the replacement for the second occurrence: ");
b=in.nextLine();
System.out.println("Enter the replacement for the third occurrence: ");
c=in.nextLine();
phrase=phrase.replaceFirst(wordRepeated, a)
.replaceFirst(wordRepeated, b)
.replaceFirst(wordRepeated, c);
System.out.println(phrase);
}
}
No comments:
Post a Comment