Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a string contains keywords?

Tags:

java

I'm writing a program that asks the user to enter keywords, and an essay, and then checks how many keywords were used in the essay.

Current output:


Enter keywords:

dog, cat

Enter essay:

i like cat

Exception in thread "main" java.lang.RuntimeException


Desired output:


Enter keywords:

dog, cat

Enter essay:

i like cat

1


Here's my code so far:

static int keywordsChecker(String shortEssay, String keywords) {
        int count = 0;

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

            String[] ary = keywords.split(",");

            if (shortEssay.contains(ary)) {
                count++;
            }
            System.out.println(count);


        }
         return count;
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter keywords: ");
        String keyword = input.nextLine();
        System.out.println("Enter essay: ");
        String essay = input.nextLine();
        keywordsChecker(essay, keyword);

    }
like image 984
user7329039 Avatar asked Dec 20 '25 15:12

user7329039


2 Answers

static int keywordsChecker(String shortEssay, String keywords)
{
    int count = 0;
    String[] ary = keywords.split(",");
    for (int i = 0; i < ary.length; i++) {
        if (shortEssay.contains(ary[i])) {
              count++;
        }
    }
    return count;
}

Just you need to call this method and get your Keywords count. :)

like image 154
Harshad Chhaiya Avatar answered Dec 23 '25 05:12

Harshad Chhaiya


This should be your approach:

  1. Split the keywords using keywords.split(",");.
  2. Loop through the keywords array obtained in step #1.
  3. check if each value from the array is available in shortEssay string or not using shortEssay.contains(ary[index]).
    1. If it's available, then increment the count variable by 1.
    2. else continue the loop.
  4. Print and/or return the count variable.

And so your keywordsChecker method looks like this:

static int keywordsChecker(String shortEssay, String keywords) {
    int count = 0;
    String[] ary = keywords.split(",");

    for (int i = 0; i < ary.length; i++) {
        if (shortEssay.contains(ary[i])) {
            count++;
        }
    }
    System.out.println(count);    
    return count;
}
like image 35
Raman Sahasi Avatar answered Dec 23 '25 04:12

Raman Sahasi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!