1

i wish to read multiple inputs on a single line in java.

Ex:

System.out.print("Input name, age, address, city: ");

user will input these details separated with space

what is expected in console:

Input name, age, address, city: Tom, 10, USA, NY

Any idea how to do this, using the Scanner class. Thanks.

Jude Niroshan
  • 3,973
  • 6
  • 36
  • 53
Akzwitch
  • 113
  • 1
  • 2
  • 13
  • 1
    ya.. use `scanner.next()`. It reads *space delimited strings* – TheLostMind May 06 '15 at 07:20
  • 1
    What have you tried already? What you try to do is not that hard using the Scanner class build in functionality. Here is the documentation of the Scanner class: http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html – Joop May 06 '15 at 07:21
  • 1
    check this answer : http://stackoverflow.com/a/11871792/2722799 – Java Man May 06 '15 at 07:29

3 Answers3

5

Reading input from the command line with the scanner can be done by doing the following

Scanner s = new Scanner(System.in);
System.out.print("Input name, age, address, city: ");
String input = s.next();
Jonas
  • 769
  • 7
  • 29
3

What you can do is:

Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String [] splitted = input.split("\\s+");

The output will be a string separated into words.

Aiyion.Prime
  • 689
  • 5
  • 18
Swati
  • 31
  • 4
2

Let us suppose if you want to take n input from console-

Scanner s = new Scanner(System.in);
List<String> listOfString=new ArrayList<String>();
for(int i=1;i<=n; i++){
    System.out.print("Input name, age, address, city: ");
    String data= s.nextLine();
    listOfString.add(data);
    }
for(String data:listOfString){
    String[] splitData= data.split("\\s+");
    for(int i=0;i<splitData.size();i++){
        System.out.print(splitData[i]);
     }
}