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..?
Use
split("\\s+")it should do the trick. It tellssplit()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