I have to search a word in a file and count how many words in and how long takes to find it. My code working well but counts the empty lines as words and I don't want the empty lines to be counted . would you look at it and see what I can add to it so the code will not count the empty lines in the file.
I have this homework where I have to search a word in a file and count how many words in and how long takes to find it. My code working well but counts the empty lines as words and I don't want the empty lines to be counted . would you look at it and see what I can add to it so the code will not count the empty lines in the file.
Here the code
import java.io.File;
import java.io.FileNotFoundException;
//scanner class for user input
import java.util.Scanner;
public class Uppgift2 {
//main function
public static void main(String[] args) {
//string to store input file name
String input_file;
//check if argument is passed in command line
if (args.length == 0) {
//if arg. is not passed initialise file to wordlist1.txt
input_file = "wordlist1.txt";
} else {
//else store the argument
input_file = args[0];
}
try {
//opening file in read mode
File fp = new File(input_file);
//scanner object for input file
Scanner scan = new Scanner(fp);
//scanner object to take word input
Scanner search = new Scanner(System.in);
String word, current;
System.out.print("Enter the word to search for>");
//read the word to search
word = search.nextLine();
//count for total number of words
int count = 0;
//variable to track if word is present or not
boolean found = false;
//store the starting time
long start = System.nanoTime();
//loop for reading all words in file
while (scan.hasNextLine()) {
//reading the current word
current = scan.nextLine();
//check if current contains the word to search
if (current.contains(word)) {
found = true;
}
//increasing count for no. of words
count++;
}
//close the input file
scan.close();
//store the end time
long end = System.nanoTime();
//print the count of words
System.out.println("\nThe file '" + input_file + "' contains " + count + " words");
//print whether the word is present or not
if (found) {
System.out.println("The word '" + word + "' exists in this file.");
} else {
System.out.println("The word '" + word + "' does not exists in this file.");
}
//calculating the time to search in ms
long time = end - start;
time = time / 1000000;
System.out.println("The search took " + time + " ms");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step by step
Solved in 2 steps