hsz hsz - 1 year ago 91
Java Question

Read integers separated with whitespace into int[] array

I read line with

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

Example input is

1 4 6 32 5

What is the fastest way to read the input and put it into an integer array

I'm also looking for some one-line solution if possible.

Answer Source

You could use Scanner:

Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNextInt())
int[] arr = list.toArray(new int[0]);

Until we have closures in java, this is probably the shortest you can get.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download