使用Scanner在一行上接受多个整数

cho*_*on4 2 java string java.util.scanner

用户需要输入一定数量的整数.相反,他们一次输入一个整数,我想让它们可以在一行上输入多个整数,然后我希望这些整数在数组中转换.例如,如果用户输入:56 83 12 99那么我想要创建一个数组{56, 83, 12, 99}

在Python或Ruby等其他语言中,我会使用一种.split(" ")方法来实现这一目标.据我所知,Java中没有这样的东西存在.有关如何接受用户输入并基于此创建阵列的任何建议都在一条线上吗?

mau*_*ris 5

使用该Scanner.nextInt()方法可以解决这个问题:

输入:

56 83 12 99

码:

import java.util.Scanner;

class Example
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int[] numbers = new int[4];
        for(int i = 0; i < 4; ++i) {
            numbers[i] = sc.nextInt();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在@ user1803551的请求上如何Scanner.hasNext()实现这个:

import java.util.*;

class Example2
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        while (sc.hasNextInt()) { // this loop breaks there is no more int input.
            numbers.add(sc.nextInt());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)