简体   繁体   中英

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:

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; 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 ?

A: YES, with streams. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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