具有未知输入行的扫描仪

Scanner with unknown lines of input

当我使用扫描仪完成输入时,我无法让我的程序知道。在我提供输入并在 IDE 终端中按两次回车后,以下代码适用于单个段落。

            Scanner scanner = new Scanner(System.in);
            ArrayList<String> als = new ArrayList<>();
            while(scanner.hasNextLine()){
                String s = scanner.nextLine();
                if(s.equals("")) break; 
                als.add(s);
            }
            scanner.close();
            for(String ss : als) System.out.println(ss);

但是我想提供多段输入,即

word word word word
word word word word

word word word word
word word word word

并将它们全部存储在数组列表中,然后打印它。

I suppose when there are only empty lines coming through. Is there a way to make it stop after two lines of ""?

在这种情况下,您可以添加一个 boolean 变量来指示最后一行是否为空:

    Scanner scanner = new Scanner(System.in);
    ArrayList<String> als = new ArrayList<>();
    boolean lastLineIsEmpty = false;
    while(scanner.hasNextLine()){
        String s = scanner.nextLine();
        if(s.equals("")) { // this line is empty
            if (lastLineIsEmpty) { // last line is also empty
                break;
            } else { // last line is not empty, set the variable to true
                lastLineIsEmpty = true;
            }
        } else { // this line is not empty, reset the variable
            lastLineIsEmpty = false;
        }
        als.add(s);
    }
    for(String ss : als) System.out.println(ss);

如果你想让它在 ""N 行之后停止,你可以改为使用 int 变量,它计算连续空行的数量扫描仪已经看到了。

您在 中针对您的问题写道:

Is there a way to make it stop after two lines of ""?

只需添加一个计数器,计算输入的连续空行数。一旦计数器大于一,您就到达了输入的末尾。

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

public class Paragraf {

    public static void main(String[] args) {

        @SuppressWarnings("resource")
        Scanner scanner = new Scanner(System.in);

        ArrayList<String> als = new ArrayList<>();
        int count = 0;
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            if (s.isEmpty()) {
                count++;
                if (count > 1) {
                    break;
                }
            }
            else {
                count = 0;
            }
            als.add(s);
        }
        als.forEach(System.out::println);
    }
}

顺便说一句,你不应该关闭 Scanner 包裹 System.in.