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

Ayman101 :

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?

hitter :

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]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31376&siteId=1