Search code examples
javalinked-listjoptionpane

Take a input and add it to Linkedlist


How do i take a input from JOptionPane.showInputDialog, split it and add it to an Arraylist?

public static void main(String[] args) {
     String acc = JOptionPane.showInputDialog("Enter a string:");
     int num = Integer.parseInt(acc);
}

Solution

  • You can use Java's String.split() to separate a string based on a separatos. For example if the words in the String are separated by a space then you can use:

    yourString.split(" ");
    

    This will return an String array. A more concrete example for what you want can be something like this

    ArrayList<String> list = new ArrayList<String>();
    String pop = "hello how are you doing";
    for(String s: pop.split(" ")){
          list.add(s);
    }
    

    The variable 'list' will contain:

            ["hello", "how", "are", "you", "doing" ]
    

    EDIT: I read in another post that you wanted to parse it to integer first, you should put that kind of things in your question. If you can then it's better if you split the string with the above method and then parse each element as you add it to an Integer ArrayList (this if the elemenets are integers).