I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first integer entered by the user. For example:
Enter multiple integers: 1 3 5
The scanner will only get the first integer 1. Is it possible to get all 3 different integers from one line and be able to use them later? These integers are the positions of data in a linked list I need to manipulate based on the users input. I cannot post my source code, but I wanted to know if this is possible.
In C++/C user can take multiple inputs in one line using scanf but in Python user can take multiple values or inputs in one line by two methods. Using split() method : This function helps in getting a multiple inputs from user.
To do this, we could read in the user's input String by wrapping an InputStreamReader object in a BufferedReader object. Then, we use the readLine() method of the BufferedReader to read the input String – say, two integers separated by a space character. These can be parsed into two separate Strings using the String.
using BufferedReader : String s[]=br. readLine(). split(" "); //s[0] contains 1st number, s1 second number and so on.
I use it all the time on hackerrank/leetcode
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String lines = br.readLine(); String[] strs = lines.trim().split("\\s+"); for (int i = 0; i < strs.length; i++) { a[i] = Integer.parseInt(strs[i]); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With