1

in one line from the standard input I have 3 types of integers: the first integer is id, the second integer is N - some number, and after that follows N integers, separeted by a single space which I want to store in array or ArrayList. How can I do this using BufferedReader? I have the following code:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] line = br.readLine().split(" ");
int ID = Integer.parseInt(line[0]);
int N = Integer.parseInt(line[1]);

My question is is there any elegant way to read the rest of the line and to store it into array?

3
  • How are those following N integers separated? Commented Jul 1, 2014 at 18:49
  • the following N integers are separated just by a single space " " Commented Jul 1, 2014 at 18:51
  • Using split with a restrictive pattern (exactly one space) requires a very accurately prepared input. If you remain with this approach, splitting on a sequence of white space is recommended ("\\s+"). Commented Jul 1, 2014 at 18:55

2 Answers 2

5

Use Scanner and method hasNextInt()

Scanner scanner = new Scanner(System.in);

while (scanner.hasNext()) {

     if (scanner.hasNextInt()) {
        arr[i]=scanner.nextInt();
        i++;
     }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

This is a general method I've posted. The OP hasn't mentioned his problem specifically. And what's the problem in reading till end of the file if the file contains all integers @laune
OP has explicitly requested how to read "N - some number, and after that follows N integer" and how to store them into an array or list. His "one line from standard input" is not his only line.
4

How can I do this using BufferedReader?

You've already read/split the line, so you can just loop over the rest of the inputted integers and add them to an array:

int[] array = new int[N];  // rest of the input

assert line.length + 2 == N;  // or some other equivalent check

for (int i = 0; i < N; i++)
    array[i] = Integer.parseInt(line[i + 2]);

This will also let you handle errors within the loop (I'll leave that part to you, should you find it necessary).

2 Comments

A check whether there are enough elements in String[] line is recommended.
@laune Sure, I incorporated that into the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.