Need help implementing a java program that can search for words in a document. T
ID: 3681849 • Letter: N
Question
Need help implementing a java program that can search for words in a document. The code should preprocces the document and store all the words found in the document and the lines where they are found in a hash table, the words will be the keys and the lines will be the values. Either a custom created hashtable or hashmap would both be acceptable. Create a main function to test using the following document ( http://pastebin.com/Lns0QZme ), this should be tested as a plain text file. For example, if the query word is "algorithm", your program should report that it is not found in the given document; and for query word "data", your program reports that it is found in six lines: [2, 4, 8, 9, 11, 12].
Explanation / Answer
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
/**
* @author Srinivas Palli
*
*/
public class SearchWord {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = null, scanner1 = null;
try {
scanner = new Scanner(new File("inputfile.txt"));
scanner1 = new Scanner(System.in);
int lineCount = 0;
Map<Integer, String> map = new HashMap<Integer, String>();
System.out.print("Enter the search word:");
String searchWord = scanner1.next();
while (scanner.hasNext()) {
lineCount++;
String line = scanner.nextLine();
if (line.contains(" " + searchWord + " ")) {
map.put(lineCount, line);
}
}
Set<Integer> set = map.keySet();
if (set.size() > 0) {
System.out.println(set);
} else {
System.out.println("Given word is not found in the directory");
}
} catch (Exception e) {
// TODO: handle exception
} finally {
scanner.close();
scanner1.close();
}
}
}
inputfile.txt
From WikiPedia
In computer science, a data structure is a particular way of storing and organizing data
in a computer so that it can be used efficiently.
Different kinds of data structures are suited to different kinds of applications,
and some are highly specialized to specific tasks. For example, B-trees are particularly
well-suited for implementation of databases, while compiler implementations usually use hash
tables to look up identifiers.
Data structures provide a means to manage large amounts of data efficiently, such as
large databases and internet indexing services. Usually, efficient data structures
are a key to designing efficient algorithms. Some formal design methods and programming languages
emphasize data structures, rather than algorithms, as the key organizing factor in software design.
Storing and retrieving can be carried out on data stored in both main memory and in secondary memory.
OUTPUT:
Enter the search word:data
[2, 4, 8, 9, 11, 12]
Enter the search word:algorithm
Given word is not found in the directory
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.