Java ArrayList, taking user input of multiple type

2020-06-20 05:11发布

问题:

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.

回答1:

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

            }

        }


回答2:

As I think there are enough answers on how to read data from System.in, I'll take a different approach here. First you should be aware that this is not the major way of getting data in java. In fact in more than 10 years I never used it. That's why there's no complete ready to use solution for give me the stuctured data into some container (like ArrayList). Instead you get simply one string per line. And you have to deal with that on your own. this process is called parsing. Depending on the complexity of the chosen syntax there are several approaches like using a parser generator if it's more complex or write the parser by hand in simpler case. I'd like to get into your first suggestion and describe it as comma separated with optional whitespace. For a syntax like this the class Scanner delivers quite some support. Numbers can be recognized and the tokenizing is done almost automatic. However, if you have more specific data you might need some aditional effort, like I demonstrated with a map of animals I used to convert that very special data type. To be flexible enough to solve all the real world problems there can't be a ready to use solution. Only comprehensive support to build your own.

  Map<String, Animal> animals = ...
  Scanner scanner = new Scanner("1, 2, 4, 257, dog, rabbit, 7, #").useDelimiter(",");
  while (scanner.hasNext()) {
    if (scanner.hasNextInt()) {
      result.add(scanner.nextInt());
    } else {
      String val = scanner.next();
      if (animals.containsKey(val)) {
        result.add(animals.get(val));
      } else {
        result.add(val);
      }
    }
  }


回答3:

One approach is to tokenize the input and then add it into an array like this:


    Scanner scn = new Scanner(System.in);
    System.out.println("Put in a set: ");
    String input = scn.nextLine();
    System.out.println(input);
    Scanner tokenizer = new Scanner(input);
    tokenizer.useDelimiter(" ");
    ArrayList<Object> arr = new ArrayList<Object>();
    while(tokenizer.hasNext())
    {
        arr.add(tokenizer.next());
        System.out.println(arr.get(arr.size()-1));
    }
    System.out.println(arr);


回答4:

you can try this code for taking input dinamically in arraylist and store in arraylist

import java.util.ArrayList;
import java.util.Scanner;

public class HelloWorld
{

 public static void main(String []args){
     Scanner sc=new Scanner(System.in);
     String j;
     ArrayList l=new ArrayList();
     for(int i=0;i<6;i++)
     {  j=sc.nextLine();
         l.add(j);
     }
    System.out.println("Hello World"+l);
 }
}