Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read multiple Integer values from a single line of input in Java?

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.

like image 858
Steven Avatar asked May 06 '14 23:05

Steven


People also ask

How do you take multiple integer inputs in one line?

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.

How can I read multiple inputs in a same line in Java?

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.

How do you declare multiple input statements in a single line in Java?

using BufferedReader : String s[]=br. readLine(). split(" "); //s[0] contains 1st number, s1 second number and so on.


1 Answers

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]);     } 
like image 127
Prasanth Louis Avatar answered Sep 21 '22 03:09

Prasanth Louis