I have written this code to determine duplicate words in the string.
but its not working.
plz help....
i am getting error in line 19.

import java.util.*;
import java.util.Scanner;

public class duplicate {
    public static void main(String[] args) {
         Scanner input = new Scanner(System.in);
       int n = input.nextInt();
System.out.println ("Input length of array:");

       String[] a = new String[n];

       for (int i = 0; i < n; i++)
       {
       	    System.out.println ("Input a[ " + i +"] :" );
       	    a[i] = new String(input.nextLine());
       }
        Set<String> s = new HashSet<String>();
        for (int i=0;i<n;i++ )
            if (!s.add(a))
                System.out.println("Duplicate detected: " + a);

        System.out.println(s.size() + " distinct words: " + s);
    }
}

Edited 6 Years Ago by bhavna13: n/a

You were getting error on line 19 because you are trying to add an array (variable a) to a HashSet of Strings. Thats why a String is expected, but you are giving it an array. Change it to if (!s.add(a[i])) .

Anyway, using Scanner.nextLine() allows users to enter multiple words per line.

import java.util.*;

public class Main
{
    public static void main(String[] args)
    {
        System.out.println("Enter words separated by spaces ('.' to quit):");
        Set<String> s = new HashSet<String>();
        Scanner input = new Scanner(System.in);
        while (true)
        {
            String token = input.next();
            if (".".equals(token))
                break;
            if (!s.add(token))
                System.out.println("Duplicate detected: " + token);
        }
        System.out.println(s.size() + " distinct words:\n" + s);
    }
}

Sample input (note the dot at the end to terminate the input): one two three four five four three two one .

Edited 6 Years Ago by sergb: n/a

This article has been dead for over six months. Start a new discussion instead.