Paulieknucklez1
Paulieknucklez1

Reputation: 1

How do I add elements to a treeset with a loop that takes user input?

I've been trying to add elements to a TreeSet using a loop that accepts user input. The problem I'm running into is that the loop I created is only filling the TreeSet with the first element that the user inputs. I was using all string variables in this example and I was also attempting to use the word 'end' as a sentinel value to terminate the loop and then print out the elements that had been added to the TreeSet. My only problem is not being able to fill the TreeSet with more than the first user input element. This is the code I used:

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

public class TestRun {
    public static void main(String[] args) {

        java.util.TreeSet wordList = new java.util.TreeSet();
        Scanner input = new Scanner(System.in);
        String word;
        System.out.print("Enter a word: ");
        wordList.add(input.next());
        while(!(word = input.nextLine()).equals("end")){
            System.out.print("Enter a word: ");
        }
        java.util.Iterator iterator = wordList.iterator();
        while(iterator.hasNext()){
            System.out.print(iterator.next() + " ");
        }
        System.out.println();
    }
}

Upvotes: 0

Views: 2747

Answers (2)

Sambit Baral
Sambit Baral

Reputation: 1

import java.util.Scanner;
import java.util.TreeSet;

public class largestandSmallestelementinanArray {
public static void main(String[] args) {

     Scanner sc =new Scanner(System.in);
     int size=0;
     System.out.println("enter the size of an array");
     size = sc.nextInt();
     TreeSet tr = new TreeSet();
     while(size>0)
     {
        tr.add(sc.nextInt());
        size--;
      }
      System.out.println(tr);           
  }
}

Upvotes: 0

Mureinik
Mureinik

Reputation: 311573

You're missing a call to wordList.add in your loop:

while(!(word = input.nextLine()).equals("end")){
    wordList.add(word); // The call you were missing
    System.out.print("Enter a word: ");
}

Upvotes: 1

Related Questions