Lab Reading a String From the Console
Lab Objective:
In this lab, you will demonstrate how to prompt the user to input a string and then read the string from console input.
Instructions
When you are developing console applications using Java, you must read input from users through the console. To read a string from the console as input in Java applications, you can use the Scanner
class along with System.in
.
Example 1 – Read String from Console Input
In this example, we shall define a scanner with the input stream, System.in
. System.in
creates a standard input stream that is already open and ready to supply input data. The Scanner
is a simple text scanner that can parse primitive types and strings using regular expressions. So, passing System.in
to Scanner
allows us to parse or read strings from the standard input stream, which is the console.
When the program is run, the execution waits after printing “Enter three words separated by spaces:,” where the user would enter a string similar to “hello world” as shown in the following console window. The program prints the string read from the console input in the next step. The whole output in the console would be as shown in the following.
Example 2: Reading a String From the Console
Output
Last updated