简体   繁体   English

Java ArrayList,在一行中获取多种类型(int,String等)的用户输入

[英]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: 我正在努力在Java上做得更好,我遇到的一个问题就是接受用户输入,所有这些都在一行中,如下所示:

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, # 1,2,4,257,狗,兔,7,#

or even 甚至

1 2 4 257 dog rabbit 7 # 1 2 4 257狗兔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. 我已经在几个地方看到过如何一次读取一个输入,但我不确定一次读取动态ArrayList的最佳方法。

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). 我真的不关心使用逗号或没有逗号的区别,因为逻辑上我认为我知道该怎么做,还没有尝试过,所以真正的主要问题如上所述(将用户输入读入ArrayList)当用户一次输入所有数字时的动态大小) 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. 只是在逻辑上陈述它的完成方式将起作用,但代码表示赞赏。

try this simple example to print the arraylist values 尝试这个简单的例子来打印arraylist值

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

            }

        }

As I think there are enough answers on how to read data from System.in , I'll take a different approach here. 我认为对于如何从System.in读取数据有足够的答案,我将采取不同的方法。 First you should be aware that this is not the major way of getting data in java. 首先,您应该知道这不是在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). 这就是为什么没有完整的准备使用解决方案为我提供结构化数据到一些容器(如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. 对于像这样的语法,类Scanner提供了相当多的支持。 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);
      }
    }
  }

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

you can try this code for taking input dinamically in arraylist and store in arraylist 您可以尝试使用此代码在arraylist中输入dinamically并存储在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);
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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