从控制台读取多行并将其存储在 Java 中的数组列表中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11621302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:48:42  来源:igfitidea点击:

Read multiple lines from console and store it in array list in Java?

javaarraylist

提问by user1547054

Can anyone please help me with the code as how to read multiple lines from console and store it in array list? Example, my input from the console is:

任何人都可以帮助我解决如何从控制台读取多行并将其存储在数组列表中的代码吗?例如,我从控制台输入的是:

12     abc      place1
13     xyz      place2

and I need this data in ArrayList.

我需要 ArrayList 中的这些数据。

So far I tried this code:

到目前为止,我试过这个代码:

Scanner scanner = new Scanner(System.in);
ArrayList informationList = new ArrayList<ArrayList>();
String information = "";
int blockSize = 0, count = 1;
System.out.println("Enter block size");
blockSize = scanner.nextInt();
System.out.println("Enter the Information ");
while (scanner.hasNext() && blockSize >= count) {
    scanner.useDelimiter("\t");
    information = scanner.nextLine();
    informationList.add(information);
    count++;
}

Any help is greatly appreciated.

任何帮助是极大的赞赏。

Input line from console is mix of string and integer

控制台的输入行是字符串和整数的混合

回答by Mike Deck

You've got a few problems.

你有几个问题。

First of all, the initialization line for your ArrayList is wrong. If you want a list of Object so you can hold both Integers and Strings, you need to put Objectinside the angle braces. Also, you're best off adding the generic type argument to the variable definition instead of just on the object instantiation.

首先,您的 ArrayList 的初始化行是错误的。如果您想要一个 Object 列表以便您可以同时保存整数和字符串,则需要将其放在Object尖括号内。此外,最好将泛型类型参数添加到变量定义中,而不仅仅是在对象实例化上。

Next, your count is getting messed up because you're initializing it to 1 instead of 0. I'm assuming "block size" really means the number of rows here. If that's wrong leave a comment.

接下来,您的计数变得一团糟,因为您将其初始化为 1 而不是 0。我假设“块大小”实际上是指此处的行数。如果这是错误的发表评论。

Next, you don't want to reset the delimiter your Scanner is using, and you certainly don't want to do it inside your loop. By default a Scanner will break up tokens based on any whitespace which I think is what you want since your data is delimited both by tabs and newlines.

接下来,您不想重置 Scanner 正在使用的分隔符,并且您当然不想在循环中执行此操作。默认情况下,扫描仪将根据我认为是您想要的任何空格来分解令牌,因为您的数据由制表符和换行符分隔。

Also, you don't need to check hasNext() in your while condition. All of the next*() methods will block waiting for input so the call to hasNext() is unnecessary.

此外,您不需要在 while 条件中检查 hasNext() 。所有 next*() 方法都会阻塞等待输入,因此不需要调用 hasNext()。

Finally, you're not really leveraging the Scanner to do what it does best which is parse tokens into whatever type you want. I'm assuming here that every data line is going to start with a single integer and the be followed by two strings. If that's the case, just make a call to nextInt() followed by two calls to next() inside your loop and you'll get all the data parsed out into the data types you need automatically.

最后,您并没有真正利用 Scanner 来做它最擅长的事情,即将令牌解析为您想要的任何类型。我在这里假设每个数据行都以一个整数开头,后面跟着两个字符串。如果是这种情况,只需在循环中调用 nextInt() 然后调用 next() 两次,您就会自动将所有数据解析为您需要的数据类型。

To summarize, here is your code updated with all my suggestions as well as some other bits to get it to run:

总而言之,这是您的代码更新了我的所有建议以及其他一些使其运行的代码:

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

public class Example {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<Object> list = new ArrayList<>();
        System.out.println("Enter block size");
        int blockSize = scanner.nextInt();
        System.out.println("Enter data rows:");
        int count = 0;
        while (count < blockSize) {
            list.add(scanner.nextInt());
            list.add(scanner.next());
            list.add(scanner.next());
            count++;
        }
        System.out.println("\nThe data you entered is:");
        System.out.println(list);
    }
}