I would do this with the nextLine()
function and a StringTokenizer
object, along with an ArrayList<Integer[]>
to store the lines of text:
Scanner sc = new Scanner(/*input source*/);
StringTokenizer input;
ArrayList<Integer[]> numbers = new ArrayList<>();
try {
while (sc.hasNextLine()) {
input = new StringTokenizer(sc.nextLine());
Integer[] n = new Integer[input.countTokens()];
for (int i=0; i<n.length; i++) {
n[x] = new Integer(input.nextToken());
}
numbers.add(n);
}
} catch (NumberFormatException ex) {
// do whatever you want here to handle non-integer input
}
This will convert each individual line into a separate Integer
array, with each array being stored in an ArrayList
. Alternatively, you could use an ArrayList<String>
and parse the integer values elsewhere in the code.
Also, for a note on the while (sc.hasNextLine())
part, you should NOT use this if your Scanner
is reading from System.in
, as this will result in an infinite loop. If your Scanner
is reading from System.in
, you should either a) have the user input a certain command to terminate the loop, or b) use a for
loop so it takes a fixed number of input lines.