Question: I need the program to be able to count Strings that are more than one word, right now in the program if you run it

I need the program to be able to count Strings that are more than one word, right now in the program if you run it and type in a string that is more than one word the program prints out that the word was found 0 times.

import java.io.File;

import java.io.FileNotFoundException;

import java.util.Scanner;

public class SearchFile extends File

{

public SearchFile(String arg0)

{//default constructor to set the file name

super(arg0);

}

public int search(String word) throws FileNotFoundException

{

Scanner obj=new Scanner(this);//read from file pointed to by this object

int count=0;

while(obj.hasNext())

{//while there are still words left to read from file

String wr=obj.next();//get the next word from file

if(wr.equals(word))//if word is equal to the word we are searching for

count++;//increment the count

}

return count;//return the count

}

public static void main(String[] args) throws FileNotFoundException

{

Scanner obj=new Scanner(System.in);//create a scanner object to read console input

System.out.println("Enter the file name to search for.");

String file=obj.nextLine();//get the string file name

System.out.println("Enter a word to search for in the file.");

String word=obj.nextLine();//get the word to search

SearchFile search=new SearchFile(file);//create an object of searchfile class

int count=search.search(word);//get the count of occurrence of word

//print the final result

System.out.println(word+" was found "+count+" times in the file "+search.getName());

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!