gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:15:57 25 4
gpt4 key购买 nike

例如,用户可以在我的程序中输入如下输入:
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());
}
}
}

最佳答案

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

boolean enterOnce = false;

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

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

关于java - 当连续按下 `System.in` 键两次时如何终止 "Enter"键盘流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31039378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com