如何在连续按下 "Enter" 键两次时终止 `System.in` 键盘流?

How to terminate `System.in` keyboard stream when "Enter" key is pressed twice in a row?

例如,用户可能会在我的程序中输入这样的输入:
71 117 48 115 127 125 117 48 121 126 48 96 117 113 115 117

或者像这样:

71 117 48  
115  
127  
125 117 48  

用户只能连续按两次"Enter"来终止输入流。

我该怎么做?

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

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> integers = new ArrayList<Integer>();
        Scanner scanner = new Scanner(System.in);

         while (scanner.hasNextInt()) {
            integers.add(scanner.nextInt());
        }
    }
}

hasNextIntnextInt忽略白色-space;所以你不能使用它们。您可以使用 hasNextLinenextLine (存储上一行);然后解析每个输入行的值(停在两个空行上)。此外,您可以使用菱形运算符 <>(我建议编程到 List 接口(而不是具体的 ArrayList 实现)。像

public static void main(String[] args) {
    List<Integer> integers = new ArrayList<>();
    Scanner scanner = new Scanner(System.in);
    String prevLine = "";
    String line = null;

    while (scanner.hasNextLine()) {
        if (line != null) {
            prevLine = line;
        }
        line = scanner.nextLine().trim();
        if (line.isEmpty() && prevLine.isEmpty()) {
            break;
        }
        String[] parts = line.split("\s+");
        for (String p : parts) {
            integers.add(Integer.parseInt(p));
        }
    }
}

您可能想要将输入的方式从 hasNextInt() 更改为 hasNextLine(),将 nextInt() 的输入方式更改为 nextLine()

boolean enterOnce = false;

while(scanner.hasNextLine()) {
    String line = scanner.nextLine();

    if(line.isEmpty())
        if(enterOnce)
            break;
        else
            enterOnce = true;
}

我发现前面的答案没有按要求运行。一种解决方案在总共两个空行之后退出循环,而不是在两个 连续 个空行之后。

2 4
<<ENTER>>
543
<<ENTER>>
---loop breaks---

另一个解决方案在单个空行之后退出,如果该空行是第一行:

<<ENTER>>
---loop breaks--- 

下面,我以不同的方式实现对连续空行的跟踪,以便正确处理这两种情况。此外,为了防止 InputMismatchExceptions,我还在将每个标记添加到整数列表之前验证了它是一个整数。

public static void main(String[] args) {
     
    // Initialise list to store the integers from input.
    List<Integer> integers = new ArrayList<>();

    // Initialise keyboard stream to get integers from keyboard.
    Scanner inputStream = new Scanner(System.in);

    // Declare a scanner to parse the lines read in from the inputStream.
    Scanner lineReader;

    // Initialise boolean to track whether two consecutive ENTER keys
    // have been pressed.
    boolean previousLineEmpty = false;
    
    // Continue taking input from the user and adding the integer input to
    // a list until ENTER is pressed twice.
    while (inputStream.hasNextLine()) {
        
        String line = inputStream.nextLine();
        
        // Determine whether the loop should break or add the integers in 
        // the line to the list.
        if (line.isEmpty()) {
          
            // If the current line and previous line are empty,
            // ENTER was pressed twice. So break.
            if (previousLineEmpty) {
                break;
            }
            
            // Otherwise, this line is empty and is an empty previous line for 
            // the next iteration.
            else {  
                previousLineEmpty = true;
            }
            
        } else {
            
            // Initialise scanner to process tokens in line.
            lineReader = new Scanner(line);
            
            // Process the tokens in the non-empty line, adding integers to the
            // list and ignoring non-integers.
            while (lineReader.hasNext()) {

                // Add token to list if it is an integer.
                if (lineReader.hasNextInt()) {
                    integers.add(lineReader.nextInt());
                } 
                // If token is not an integer, instead advance to next token.
                else {
                    lineReader.next();
                }
            }   
            
            // In the next iteration, this non-empty line is the previous 
            // line. Set boolean to false.
            previousLineEmpty = false;
        }  
    }