Write a java program that calculates the number of duplicate words in a sentence. You may assume that the input consists only 52 English characters with a single white-space as the separator between words (not punctuations in the inputted sentence). You need consider uppercase and lowercase letters the same. You may get the input from the keyboard. (You need to use Set and/or Hashset).
What I have so far
import java.util.HashSet;
import java.util.Scanner;
public class Duplicate {
int counter;
int e;
//read a String
Scanner sc = new Scanner(System.in);
HashSet hs = new HashSet <String>();
{
System.out.print("Type a sentence: ");
String s = sc.nextLine();
//String chara[] = sl.split();
/* ForEach e in as{
e = toUppercase();*/
if(hs.contains(e)) counter++;
else hs.add(e);
System.out.println(counter++);
}
}
Solution:
import java.util.*;
public class Duplicate{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
HashSet<String> hs= new HashSet<>();
System.out.print("Type a sentence: ");
String s = sc.nextLine();
//adding space in the end of the string
s=s+" ";
//storing string into an array
String[] arr = s.split(" ");
//storing string to uppercase
s=s.toUpperCase();
int count=0;
for(int i=0; i<arr.length; i++){
String s1=arr[i];
//checking whether the set contains the string or not
if(hs.contains(s1))
count++;
else
hs.add(s1);
}
System.out.println("No of duplicates are " +count);
}
}
Get Answers For Free
Most questions answered within 1 hours.