简体   繁体   中英

Read words using scanner in Java

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.

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();

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.

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]);
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM