Shivam
Shivam

Reputation: 103

java: taking input with BufferedReader- more than one spaces

I have space separated integers in one line and want to input them using BufferedReader. ** There may be more than one spaces between the integers. There may be leading and trailing spaces**

Right now I have following code ,

`

  int[] a = new int[1000001]; // integer array

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

  int n; // no of integers

  int n =  Integer.parseInt(br.readLine());

  String[] s = br.readLine().split(" ");  //taking input

      for(int i=1;i<=n;++i)
      {

           a[i] = Integer.parseInt(s[i]);
      }

`

Its not working.Please help. Any help or suggestion would be appreciated . Thanks.

Edit:1 - I used split("\s+"). But this cares for more than one spaces between integers... What about leading and trailing spaces..?? How to deal with them..?

Upvotes: 1

Views: 3064

Answers (2)

user3679868
user3679868

Reputation: 693

Use split("\\s+") it should do the trick. It tells split() to use one or more space characters as a delimiter between two tokens.

Also you should allocate you int[] after you have read the number of int to read instead of allocating one that is way too big, you waste memory for nothing

Upvotes: 2

radar
radar

Reputation: 605

You can first read the line, then use a regex to replace all whitespace with only one space. Then you can split it as you do above. Let me know if you need further help or code examples.

Edit: the NumberFormatException could be because the Integer.parseInt is trying to parse something outside of the value of an integer. Try Long.parseLong instead.

Upvotes: 0

Related Questions