user4766730
user4766730

Reputation:

Printing data from a file

So I am stuck trying to search a file for keywords in a sentence and print the found sentence. I have some code which searching the input for matching words but I do not know how to go around searching a file for those keywords based on user input. Am I going in the right direction?

static String [ ] matchwords = {"get","think","go", "talk","choose"};
static List words = Arrays.asList(matchwords);

public static void main(String args[]){
    Scanner console = new Scanner(System.in);
    String input = console.nextLine().toLowerCase();
    List line = Arrays.asList(input.split(" "));
    int numberofWords =0;

    numberofWords = check(line, numberofWords);
    System.out.println("Matched words is : "+numberofWords);
}

public static int check(List list, int count){
    for(int j=0;j<list.size();j++)
        if(words.contains(list.get(j))){
            list.remove(j);
            check(list, count);
            count++;
        }

    return count;
}

Upvotes: 1

Views: 58

Answers (1)

Code Whisperer
Code Whisperer

Reputation: 1041

Use contains() for each word you are looking for and increment a counter once you hit a match.

String input = console.nextLine().toLowerCase();
List<Integer> matches = new ArrayList<Integer>();
for (int i = 0; i < matchwords.length; i++) {
    if (input.contains(matchwords[i]) {
        matches.add(i); // stores indices of the words that had a match
        // matches.length will be the number of matches (previously count)
    }
}

Upvotes: 2

Related Questions