Question

This is my code so far below

import java.util.*;
import java.io.*;
public class USconstitution   
{
  public static void main(String [] args) throws Exception
  {
     Scanner inFile = new Scanner(new File("constitution.txt"));
     int x = 0;
     int keyword1 = 0;
     Scanner keyboard = new Scanner(System.in);
     System.out.println("Enter a word from the keyboard");
     String input = keyboard.next();
     while(inFile.hasNext())
     {
        String word = inFile.next();
        x++;
        if(input.equalsIgnoreCase(word))
           keyword1++;
     }
     //System.out.println("\n" + x);
     System.out.println("The constitution has " + x + " words");
     System.out.println("The first keyword shows up " + keyword1 + " times in the  

     constitution");
  }
}

THE OUTPUT SO FAR =

Enter a word from the keyboard

President

The constitution has 4610 words

The first keyword shows up 20 times in the constitution


My goal for this program is to search through a text file that has been given to me which contains the US Constitution.

The first part simply counts how many words are in the text file, the next bit that I am trying to do is allow people to search for certain keywords and have it search the text file and say how many times that word shows up.

I was thinking of having the prompt ask what keywords the user wishes to enter and have it use the split method to create each word as an individual string and search for that in the file then output how many times it appears. Although I am not so sure how to go about this, any help would be greatly appreciated!

Was it helpful?

Solution

Try this:

public static void main(String[] args)
{       
    String text = "the quick brown fox jumps fox fox over the lazy dog brown";
    String[] textArray = text.split(" ");
    String[] keysToSearch = {"the", "fox", "dog"};
    int count = 0;
    System.out.println(text);

    for(String key: keysToSearch)
    {                       
        for(String s : textArray)
        {
            if(key.equals(s))
            {
                count++;
            }               
        }
        System.out.println("Count of ["+key+"] is : "+count);
        count=0;
    }
}

Output:

the quick brown fox jumps fox fox over the lazy dog brown
Count of [the] is : 2
Count of [fox] is : 3
Count of [dog] is : 1

OTHER TIPS

Take the code that does the check out of the main method and put it in a separate method that takes a single keyword as a parameter. Then you can split the input string given from the console using

String[] keywords = input.split(" "); // will split at spaces

Then all you have to do is loop through all of the keywords in your array

for(int  i = 0; i < keywords.length; i++){

    yourCountMethod(keywords[i]);

}

This is just the general idea, obviously you will have to change the code to suit.

Hope that helps :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top