(Java) Your project will ask the user to enter the entire the path and name of a
ID: 3674626 • Letter: #
Question
(Java) Your project will ask the user to enter the entire the path and name of a text file and ask the user for a word to search for. Then, your project will report on the screen how many times the word appears in the text and the line numbers where the word is found.
The only methods of the String and StringBuilder class are allowed to use are the length(), charAt(), toUpperCase(), toLowerCase()
Write this project using the object-oriented paradigm. The main() method will only prompt the user and read input, call the methods of the other class, and print the output to the screen.
Explanation / Answer
import java.io.File;
import java.util.Scanner;
/**
* @author Srinivas Palli
*
*/
public class SearchWord {
/**
* METHOD to count no times found word and line no
*
* @param word
* @param file
*/
public static void countWord(String word, File file) {
int count = 0;
try {
Scanner scanner = new Scanner(file);
int line = 0;
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
line++;
if (nextToken.length() == word.length()) {
int matchCount = 0;
for (int i = 0; i < nextToken.length(); i++) {
if (word.charAt(i) == nextToken.charAt(i)) {
matchCount++;
} else {
break;
}
if (matchCount == nextToken.length()) {
System.out.println("Word founds at Line :" + line);
count++;
}
}
}
}
if (count != 0) {
System.out.println("Word found " + count + " time.");
} else {
System.out.println("Word not found ");
}
scanner.close();
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
String fileName;
String word;
System.out.print("Enter the File Name :");
fileName = scanner.nextLine();
File file = new File(fileName);
System.out.print("Enter the word to search:");
word = scanner.next();
countWord(word, file);
} catch (Exception e) {
// TODO: handle exception
} finally {
scanner.close();
}
}
}
words.txt:
Hai
How
Are
How
Things
Doing
Hai
Iam
Fine
OUTPUT:
Enter the File Name :words.txt
Enter the word to search:Hai
Word founds at Line :1
Word founds at Line :7
Word found 2 time.
Enter the File Name :Words.txt
Enter the word to search:Come
Word not found
Enter the File Name :words.txt
Enter the word to search:How
Word founds at Line :2
Word founds at Line :4
Word found 2 time.
Enter the File Name :words.txt
Enter the word to search:are
Word founds at Line :3
Word found 1 time.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.