Create a program called PhraseCounter that counts the number of times a particul
ID: 3642619 • Letter: C
Question
Create a program called PhraseCounter that counts the number of times a particular phrase in a bodyof text. The user will enter the text line by line, ending with a blank line. The user will then enter a
phrase; this phrase may be more than one word. Your program needs to scan through the text to
find out how many times that phrase occurs in the text. Your program should not be case-use basic methods which we covered charAt(int) compareTo(String) equals(String) length() substring(int, int)sensitive.
Explanation / Answer
Hi, Please find below the program. It get the line by line until a blank line is entered. And ask for a Phrase. Check whether the phrase is there in the list of phrase entered. It used the compareTo method to compare, I understand your question ask to use these methods (use basic methods which we covered). There is no necessity to use other methods. import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class PhraseCounter { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String line = ""; List stringList = new ArrayList(); System.out.println("Enter the text"); while (!(line = sc.nextLine()).isEmpty()) { stringList.add(line); } System.out.println("Enter the Phrase"); String phrase = sc.next(); int count = 0; for (String str : stringList) { if (str.compareTo(phrase) == 0) count++; } System.out.println("Number of times the Phrase occurred: " + count); } } Output: Enter the text hello hi how are you hello hello Enter the Phrase hello Number of times the Phrase occurred: 3 Hope it helps you.Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.