Write a program called SearchText. java that: 1. Prompts the user for a text fil
ID: 3817945 • Letter: W
Question
Write a program called SearchText. java that: 1. Prompts the user for a text file pathname. 2. Prompts the user for a search string. 3. Reads in all of the text in the file. 4. Splits that text into an array of words. 5. Prints a list of every word that contains the search string. 6. After that list, prints a count of how many words contain that search string. For example, running this program for the file constitution. txt and using the search string qu produces the output: Tranquility requisite subsequent Consequence equally equally disqualification require question questioned question Marque Square require Consequence Marque equal equal quorum equal require EquityExplanation / Answer
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class SearchText {
public static String[] readFile(String filename)
{
List<String> stringList = new ArrayList<>();
FileReader fr = null;
try {
fr = new FileReader(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Scanner sc = new Scanner(fr);
while(sc.hasNext())
{
stringList.add(sc.next());
}
sc.close();
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
return stringList.toArray(new String[stringList.size()]);
}
public static void search(String[] wordArray, String searchString)
{
int count = 0;
for(int i = 0; i < wordArray.length; i++)
{
if (wordArray[i].toLowerCase().contains(searchString.toLowerCase()))
{
System.out.println(wordArray[i]);
count++;
}
}
System.out.println("Number of words containing "" + searchString + "": " + count);
}
public static void main(String[] args)
{
System.out.print("Enter a file name: ");
Scanner sc = new Scanner(System.in);
String fileName = sc.nextLine();
String[] wordArray = readFile(fileName);
System.out.print("Enter a string to search: ");
String searchString = sc.nextLine();
search(wordArray, searchString);
sc.close();
}
}
// Sample run
Enter a file name: SearchText.java
Enter a string to search: wor
wordArray,
wordArray.length;
(wordArray[i].toLowerCase().contains(searchString.toLowerCase()))
System.out.println(wordArray[i]);
words
wordArray
search(wordArray,
Number of words containing "wor": 7
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.