Hi,
I know you can set the input for a scanner in Java. Is it possible to feed an array to the scanner?
Hi,
I know you can set the input for a scanner in Java. Is it possible to feed an array to the scanner?
There is nothing built in, but you could certainly join all of the elements in your array and pass the resulting string into the Scanner constructor.
A solution with better performance but a greater time investment is to implement Readable by wrapping your array, and keeping track of the current element in the array and the current position in that element's string representation. You can then fill the buffer with data from the backing array as the Scanner reads from your Readable object. This approach lets you lazily stream data from your array into the Scanner, but at the cost of requiring you to write some code.
Use the Arrays.toString() method on the array. For example:
int[] arrayOfInts = {1, 2, 3};
Scanner s = new Scanner(Arrays.toString(arrayOfInts));
while (s.hasNext()) {
System.out.println(s.next());
}
Will print out:
[1,
2,
3]