1. Engineering
  2. Computer Science
  3. i need help with my java code a user enters...

Question: i need help with my java code a user enters...

Question details

I need help with my Java code. A user enters a sentence and the program will tell you what words were duplicated and how many times. If the same word is in the sentence twice, but one is capitalized, it will not count it as a duplicate. How can I make the program read the same word as the same word, even if one is capitalized and the other is not?

For example, "the" and "The" should be counted as a duplicate word.

import java.util.HashSet;
import java.util.Collections;
import java.util.Set;
import java.util.Scanner;
public class DuplicateWords {
    public static void main(String[] args) {
        //input string
    // String input = "I am taking Advanced Java this spring semester "
    //         + "I will be qualified ton graduate next fall semester.";
     Scanner in = new Scanner(System.in);
    System.out.print("Enter a sentence: ");
     String sentence = in.nextLine();
   
     //call method duplicates using isentance as argument
     Set duplicatewords = duplicates(sentence);
     System.out.println("The duplicate words in the sentence: " + duplicatewords);
   
}

    //define metiod duplicates to find duplicates in sentence
    public static Set duplicates(String sent)
    {
        //variabes
        int i=0, count=0;
        //use if loop to empty sgring
        if(sent == null || sent.isEmpty())
        {
            return Collections.emptySet();
        }
          //the fiunction for new set
          Set duplicatewords = new HashSet<>();
          //use split function to check duplicates
       
         String[] words = sent.split("\\s+");
          Set s = new HashSet<>();
          //loop to find duplicates in sentence and #
          for(i=0; i<words.length; i++)
          {
              if(!s.add(words[i]))
              {
          duplicatewords.add(words[i]);
          count++;
    }
          }
        
          //display # of duplicates
          System.out.println("\nThe number of duplicates "
          + "in the sentance: " + count);
        
          //return duplicate words
          return duplicatewords;
    }

  
}

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution