For this need to write 2 different small programs: Assume that all forms of prof
ID: 3581392 • Letter: F
Question
For this need to write 2 different small programs:
Assume that all forms of profane words are profane.
That is hate hated hater all profane
Problem 1 10 points
Write a Java program which reads a s sentence (using scanner) and prints the starting index of first profane word.
The profane words are devil, hate, hell
Example: The devil won by hate
Your profane word index starts at 4
Example: God lost
There is no profane word in the sentence
Problem 2 20 points
The profane words are "hate" "devil" "hell" "gloomy" and "evil"
Read a sentence and check If it has profane word. Assume a sentence has only one profane word or no profane words.
If a profane word occurs,delete the word and write the sentence
Sample output:
The man is devil at heart
The man s at heart
The man is gloomier at heart
The manl is gloomier at heart
Explanation / Answer
Please find my my program.
########## Program1 ########
import java.util.Scanner;
public class Problem1 {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
String[] profane = {"devil", "hate", "hell"};
System.out.println("Enter a sentence: ");
String sentence = sc.nextLine();
int index = -1;
for(String s : profane){
int t = sentence.indexOf(s);
if( t != -1 && t < index)
index = t;
else if(index == -1)
index = t;
}
if(index == -1){
System.out.println("There is no profane word in the sentence");
}else{
System.out.println("Your profane word index starts at "+index);
}
}
}
/*
Sample run:
Enter a sentence:
The devil won by hate
Your profane word index starts at 4
Enter a sentence:
God lost
There is no profane word in the sentence
*/
############ Program2 #############
import java.util.Scanner;
public class Program2 {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
String[] profane = {"hate", "devil", "hell", "gloomy", "evil"};
System.out.println("Enter a sentence: ");
String sentence = sc.nextLine();
int index = -1;
for(String s : profane){
index = sentence.indexOf(s);
if( index != -1){
String firstPart = sentence.substring(0, index);
String secondPart = sentence.substring(index+s.length());
System.out.println(firstPart+secondPart);
break;
}
}
if(index == -1)
System.out.println(sentence);
}
}
/*
Sample run:
Enter a sentence:
The man is devil at heart
The man is at heart
Enter a sentence:
The man is gloomier at heart
The man is gloomier at heart
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.