简体   繁体   English

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

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

I have a problem of finding a piece of code to read a bunch of integers into a list, i tried this but in vain:我在找到一段代码将一堆整数读入列表时遇到了问题,我试过这个但徒劳无功:

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

Can you help me please?你能帮我吗?

Try this example code, see if it works for you.试试这个示例代码,看看它是否适合你。

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);
    }
}

This code in console with input 1 2 3 yields:此代码在控制台中输入1 2 3产生:

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

Q: Can I read multiple integers from a single line of input without using a loop?问:我可以在不使用循环的情况下从一行输入中读取多个整数吗?

A. With parallel processing, possibly yes; A. 使用并行处理,可能是; but with normal sequential processing, NO, there will always be a loop involved.但是对于正常的顺序处理,不,总会有一个循环。

Q: Can I, however, without benefit of parallel processing, read multiple integers from a single line of input without using one of the loop statements for , while , or do ?问:但是,如果没有并行处理的好处,我可以从一行输入中读取多个整数而不使用forwhiledo循环语句for吗?

A: YES, with streams. A:是的,使用流。 But don't think that by eliminating the explicit loop statement you've eliminated the actual loop itself ;但是不要认为通过消除显式循环语句就消除了实际循环本身 it's still there, just hidden away inside the stream machinery instead of clearly visible in your own code.它仍然存在,只是隐藏在流机制中,而不是在您自己的代码中清晰可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM