Reputation: 1
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
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
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