Java : 从控制台只获取一行整数?

Java : Get only 1 line of integers from the console?

我最近使用了 Java,但我遇到了一些控制台输入问题。

基本上,我想以如下格式从控制台读取一个整数数组:

1 2 3 4 5 6

我查看了论坛上的一些示例,并决定使用扫描器 nextInt() 方法来完成此操作。

我的代码目前看起来像这样:

Scanner get = new Scanner(System.in);
List<Integer> elements = new ArrayList<>();

while (get.hasNextInt()) {           
        elements.add(get.nextInt());
    }

此代码的问题在于,当我在控制台上点击 "Enter" 时,while 循环不会停止。 这意味着在我输入一些数字 (1 3 5 7) 然后按回车键后,程序不会继续执行,而是等待更多的整数。它停止的唯一方法是我向控制台输入一封信。

我尝试在我的 while 循环中添加 !get.hasNextLine() 作为条件,但这没有帮助.

如果有人知道我该如何解决这个问题,我将非常感激。

您可以阅读一行,然后用它来构造另一行 Scanner。像,

if (get.hasNextLine()) {
    String line = get.nextLine();
    Scanner lineScanner = new Scanner(line);
    while (lineScanner.hasNextInt()) {          
        elements.add(lineScanner.nextInt());
    }
}

Scanner(String) 构造函数(根据 Javadoc) 构造一个新的 Scanner 生成从指定字符串扫描的值。

Scanner get = new Scanner(System.in);
String arrSt = get.next();
StringTokinizer  stTokens = new StringTokinizer(arrSt," ");
int [] myArr = new Int[stTokens.countTokens()];
int i =0;
while(stTokens.hasMoreTokens()){
    myArr[i++]=Integer.parseInt(stTokens.nextToken());
}

您可以使用以下内容。用户只需输入每个整数而无需按回车键并在最后按回车键。

Scanner get = new Scanner(System.in);
List<Integer> elements = Stream.of(get.nextLine().split(" "))
                               .map(Integer::parseInt)
                               .collect(Collectors.toList());

如果你想阅读只有一行最简单的答案可能是最好的:)

Scanner in = new Scanner(System.in); String hString = in.nextLine(); String[] hArray = hString.split(" ");

现在,在数组 hArray 中,您拥有来自输入的所有元素,您可以像 hArray[0]

那样调用它们