简体   繁体   English

Java采用多行输入

[英]Java Taking Multiple Line Input

How do I go about taking input that is multiple lines, such as 我该如何进行多行输入,例如

4 2 9
1 4 2
9 8 5

and placing it into an array of that is big enough to hold each line with no empty positions, or an arraylist. 并将其放入足够大的数组中,以容纳没有空位置的每一行或一个arraylist。 I've tried many ways to do this and cannot find a solution. 我尝试了许多方法来执行此操作,但是找不到解决方案。 For example, if the user copied and pasted the above snippet as input, I want an array or arraylist to hold 例如,如果用户复制并粘贴了上面的代码片段作为输入,我希望保留一个数组或arraylist

["4 2 9", "1 4 2", "9 8 5"] 

try this: 尝试这个:

List<String> list = new ArrayList<String>();
 while((str = in.readLine()) != null){
 list.add(str);
}

You can use Scanner to read the input from console. 您可以使用扫描仪从控制台读取输入。

Try something like this: 尝试这样的事情:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    List<String> list = new ArrayList<String>();

    while(scan.hasNextLine()) {
        String str = scan.nextLine();
        System.out.println(str);
        list.add(str);
    }

    System.out.println(java.util.Arrays.toString(list.toArray()));

    scan.close();
}

Try calling nextLine 尝试致电nextLine

Scanner s = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
while (s.hasNextLine()) {
    list.add(s.nextLine());
}

System.out.println(list);

Note that the scanner will keep prompting for input. 请注意,扫描仪将继续提示输入。 To stop this, you need to enter an end of line character. 要停止此操作,您需要输入行尾字符。 See this answer for how to do this. 有关此操作的信息,请参见此答案

Example input/output: 输入/输出示例:

4 2 9
1 4 2
9 8 5
^D
[4 2 9, 1 4 2, 9 8 5]

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

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