Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 859
trueCamelType Avatar asked Sep 15 '13 01:09

trueCamelType


People also ask

Can an ArrayList hold multiple data types?

It is more common to create an ArrayList of definite type such as Integer, Double, etc. But there is also a method to create ArrayLists that are capable of holding Objects of multiple Types. We will discuss how we can use the Object class to create an ArrayList. Object class is the root of the class hierarchy.

Can we store String and integer together in an ArrayList in Java?

Yeah, you can create an ArrayList<Object> but having said that, my advice for you is this: don't. Don't create Lists with mixed types since this suggests that your program design is broken and needs to be improved so that this sort of monster isn't needed.

How do you take multiple inputs from an ArrayList?

ArrayList<Integer> numbers = new ArrayList<Integer>(); //insert into array if > 0 int x = sc. nextInt(); if(x > 0){ numbers. add(x); } //square numbers array for (int i = 0; i < numbers. size(); ++i) { numbers.


1 Answers

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

            }

        }
like image 126
Nambi Avatar answered Sep 22 '22 17:09

Nambi