0

How can I read in one line of integers at a time before moving on to the next one?

I'm receiving input like below (ignore bullet points):

  • 4 -space- - space- 2 - space- - space- - space- 3
  • -space- 84 -space -space- 6
  • 2 -space- -space- -space- 8 -space- -space- 19

where for each row of integers I want to perform operations on only that row. Then I want to get the next row and perform operations on that one and so on.

I won't know how many spaces there are between numbers and I'm currently using Java's scanner.

redpanda12
  • 13
  • 3

2 Answers2

1

There might be better way and one possible way could be reading whole line as a single string and then splitting each on spaces. These will be string though and you have to change it to integer.

Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
String[] splitStr = str.split(" ");

for(String s: splitStr)
     System.out.println(s);
student
  • 13,946
  • 4
  • 27
  • 43
0

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.

Bethany Louise
  • 636
  • 7
  • 13