我可以在不使用循环的情况下从 Java 中的单行输入中读取多个整数吗

Can i read multiple integers from single line of input in Java without using a loop

我在找到一段代码来将一堆整数读入列表时遇到了问题,我试过了但没有成功:

public static void main(String[] args){
    int[] a = in.readInts(); //in cannot be resolved
    StdOut.println(count(a)); //StdOut cannot be resolved
}

你能帮帮我吗?

试试这个示例代码,看看它是否适合你。

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

public class Main {
    public static void main(String[] args) {
        int amount = 3; // Amount of integers to be read, change it at will.
        Scanner reader = new Scanner(System.in);
        System.out.println("Please input your numbers: ");

        int num; // integer will be stored in this variable.
        // List that will store all the integers.
        ArrayList<Integer> List = new ArrayList<Integer>();
        for (int i = 0; i < amount; ++i) {
            num = reader.nextInt();
            List.add(num);
        }
        System.out.println(List);
    }
}

控制台中的这段代码输入 1 2 3 产生:

Please input your numbers:
1 2 3 
[1, 2, 3]

问:我可以在不使用循环的情况下从一行输入中读取多个整数吗?

一个。并行处理,可能是;但是对于正常的顺序处理,不,总会有一个循环。

问:但是,在没有并行处理的情况下,我是否可以在不使用 循环语句 for 的情况下从单行输入中读取多个整数? whiledo?

A:是的,有流。但是不要认为通过消除显式循环 语句 你已经消除了实际的 循环本身 ;它仍然存在,只是隐藏在流机制中,而不是在您自己的代码中清晰可见。