I am using BufferedReader class to read inputs in my Java program. I want to read inputs from a user who can enter multiple integer data in single line with space. I want to rea
Late to the party but you can do this in one liner in Java 8 using streams
.
InputStreamReader isr= new InputStreamReader();
BufferedReader br= new BufferedReader(isr);
int[] input = Arrays.stream(br.readLine().split("\\s+")).mapToInt(Integer::parseInt).toArray();
I use this code for List:
List<Integer> numbers = Stream.of(reader.readLine().split("\\s+")).map(Integer::valueOf).collect(Collectors.toList());
And it is almost the same for array:
int[] numbersArray = Arrays.stream(reader.readLine().split("\\s+")).mapToInt(Integer::valueOf).toArray();
Integer.parseInt(br.readLine())
-> Reads a whole line and then converts it to Integers.
scanner.nextInt()
-> Reads every single token one by one within a single line then tries to convert it to integer.
String[] in = br.readLine().trim().split("\\s+");
// above code reads the whole line, trims the extra spaces
// before or after each element until one space left,
// splits each token according to the space and store each token as an element of the string array.
for(int i = 0; i < n; i++)
arr[i] = Integer.parseInt(in[i]);
// Converts each element in the string array as an integer and stores it in an integer array.
Well as you mentioned there are two lines- First line takes number of integers and second takes that many number
INPUT: 5 2 456 43 21 12
So to address this and covert it into array -
String[] strs = inputData.trim().split("\\s+"); //String with all inputs 5 2 456 43 21 12
int n= Integer.parseInt(strs[0]); //As you said first string contains the length
int a[] = new int[n]; //Initializing array of that length
for (int i = 0; i < n; i++)
{
a[i] = Integer.parseInt(strs[i+1]); // a[0] will be equal to a[1] and so on....
}
If you want to read integers and you didn't know number of integers
String[] integersInString = br.readLine().split(" ");
int a[] = new int[integersInString.length];
for (int i = 0; i < integersInString.length; i++) {
a[i] = Integer.parseInt(integersInString[i]);
}
Try the next:
int a[] = new int[n];
String line = br.readLine(); // to read multiple integers line
String[] strs = line.trim().split("\\s+");
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(strs[i]);
}