Search code examples
javaarraysarraylistuser-input

Java ArrayList, taking user input of multiple types(int, String etc.) in one line


I'm working on getting a little better at Java, and a problem I've run into is taking user input, all in one line like this:

System.out.println("Please input numbers that you would like to work with");

    //Read in user input into ArrayList, taking into account that they may input Strings or anything else.

Assuming the user inputs something like this

1, 2, 4, 257, dog, rabbit, 7, #

or even

1 2 4 257 dog rabbit 7 #

I've seen in several places how to read in one input at a time, but I wasn't sure of the best way to read in a dynamic ArrayList all at once.

I'm not really concerned with the difference in doing it with commas or without commas since logically I think I know how to do that, and haven't tried yet, so really the main problem is as stated above (reading user input into ArrayList of dynamic size when user inputs all numbers at once). Thanks, and I'm not necessarily looking for code, this isn't homework, just wondering best way to do this. Just stating logically how it's done will work, but code is appreciated.


Solution

  • try this simple example to print the arraylist values

         import java.util.*;
            class SimpleArrayList{
                public static void main(String args[]){
                    List l=new ArrayList();
                    System.out.println("Enter the input");
                    Scanner input=new Scanner(System.in);
    
                     String a =input.nextLine();
                     l.add(a);
           // use this to iterate the value inside the arraylist.
          /* for (int i = 0; i < l.size(); i++) {
              System.out.println(l.get(i));
                  } */
                        System.out.println(l);
    
                }
    
            }