我如何在Java中读取多行文本,行之间有空格

时间:2018-11-29 15:59:23

标签: java arrays list input

我想读取字符串ArrayList中的那三行,我的代码是在ArrayList中添加一些内容。 输入:

1,1,1,1,0,1,1,0

0,1,1,0,0,1,1,1

1,1,1,1,1,1,1,0

Segm.java:

import java.util.*;
public class Segm 
{
    public static void main(String[] args) 
    {
        Scanner scan=new Scanner(System.in);
        ArrayList<String> s=new ArrayList();
        while(scan.hasNextLine())
        {
            String a=scan.nextLine();
            if(a.isEmpty())
            {
                scan.nextLine();
            }
            s.add(a);
        }
    }
}

4 个答案:

答案 0 :(得分:3)

我会做类似的事情:

while(scan.hasNextLine())
{
    String a=scan.nextLine();
    if( !a.isEmpty())
    {
        s.add(a);
    }
}

也就是说,不要假设只有一个空白行。上面的代码将忽略所有空白行。

答案 1 :(得分:0)

在随后的对nextLine()的调用中,您不会再次分配a变量,

String a=scan.nextLine();
if(a.isEmpty())
{
    a=scan.nextLine(); // you are doing scan.nextLine(); only and not updating a
}
s.add(a);

另外,要处理多个空行,您应该考虑在代码中使用while循环而不是if语句块

答案 2 :(得分:0)

这是怎么做的。忽略空行并在用户输入q

时退出
Scanner scan = new Scanner(System.in);
ArrayList<String> strings = new ArrayList<>();
while(scan.hasNextLine()) {
    String a = scan.nextLine();
    if (a.trim().isEmpty()) {
         continue;
    }
    if (a.equalsIgnoreCase("Q")) {
        break;
    }
   strings.add(a);
}

答案 3 :(得分:0)

   Scanner scan =new Scanner(System.in);
    ArrayList<String> s=new ArrayList();
    while(scan.hasNextLine())
    {
        String a=scan.nextLine();

        if(a.equals("fine"))
            break;
        if(!a.isEmpty())
        {
        s.add(a);

        }
    }