Reading system input using Scanner

Download java eBook

Example

Scanner scanner = new Scanner(System.in); //Scanner obj to read System input
String inputTaken = new String();
while (true) {
    String input = scanner.nextLine(); // reading one line of input
    if (input.matches("\\s+"))         // if it matches spaces/tabs, stop reading
        break;
    inputTaken += input + " ";
}
System.out.println(inputTaken);

The scanner object is initialized to read input from keyboard. So for the below input from keyboar, it'll produce the output as Reading from keyboard

Reading
from
keyboard
  //space

Stats

Contributors: 2
2016-04-22
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook