Exercise
Search in file
Objetive
Create a program that reads a text file, saves its content to an ArrayList, and asks the user to enter sentences to search within the file.
The program should ask the user to enter a word or sentence and display all the lines that contain the word or sentence. It should then prompt the user to enter another word or sentence and repeat the process until the user enters an empty string.
Example Code
package Contains;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
java.io.FileReader myfile = new java.io.FileReader("text.txt");
java.io.BufferedReader myfileBufferedReader = new java.io.BufferedReader(myfile);
try
{
ArrayList list = new ArrayList();
String line;
do
{
line = myfileBufferedReader.readLine();
if (line != null)
{
list.add(line);
}
} while (line != null);
myfile.close();
String sentence;
boolean exit = false;
do
{
System.out.print("Enter word or sentence: ");
sentence = new Scanner(System.in).nextLine();
if (sentence.equals(""))
{
exit = true;
}
else
{
for (int i = 0; i < list.size(); i++)
{
String sentenceList = (String)list.get(i);
if (sentenceList.contains(sentence))
{
System.out.println(sentenceList);
}
}
}
} while (!exit);
}
catch (RuntimeException e)
{
System.out.println("Error, " + e.getMessage());
}
}
}