简体   繁体   中英

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();
    }
}

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: ");
}
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);           
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM