0

I would like to print out strings without duplicated words. The first int determines how many Strings I have, followed by the strings with duplications. But in my output I get an empty line at the first line and I would like to know how to get rid of this first empty line? Thank you for your time and help!

Input Example:
3
Goodbye bye bye world world world
Sam went went to to to his business
Reya is is the the best player in eye eye game

Output:
*empty line*
Goodbye bye world 
Sam went to his business 
Reya is the best player in eye game

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int lines= sc.nextInt()+1;
    String [] str= new String[lines];

    for(int i=0;i<lines;i++) {          
        str[i]=sc.nextLine();       
    }

    for(int i=0;i<lines;i++) {
        String temp= str[i];

        String[] strWords = temp.split("\\s+");

        LinkedHashSet<String> hstr = new LinkedHashSet<String> ();

        for(int j=0;j<strWords.length;j++) {
            hstr.add(strWords[j]);
        }

        String[] strArr = new String[hstr.size()];
        hstr.toArray(strArr);

        for(int k=0;k<hstr.size();k++) {
            System.out.printf("%s", strArr[k] + " ");
        }      

        System.out.println();       
    }   
    sc.close(); 
}
Alox
  • 601
  • 10
  • 21
Foxxy
  • 3
  • 1

1 Answers1

0

When you type 3 for lines, this code:

int lines= sc.nextInt()+1;  // why + 1?
String [] str= new String[lines];

for(int i=0;i<lines;i++) {
   str[i]=sc.nextLine();
}

creates an array of 4 elements with the 1st being an empty string ""

forpas
  • 117,400
  • 9
  • 23
  • 54