User Input


The Scanner class is used to get user input from the console, and it is found in the java.util package. To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. The following example reads input String from the console by using the method nextLine(System.in) method, where System.in represents the standard input stream.

MyScanner.java (reading user input from the console)
// Import the Scanner class.
import java.util.Scanner;

class MyScanner {
  public static void main( String[ ] args ) {
    // Create a Scanner object.
    Scanner myObj = new Scanner( System.in );
    System.out.print( "Enter username: " );
    // Read user input.
    String userName = myObj.nextLine( );
    // Output user input.
    System.out.println( "Username is: " + userName );
  }
}
Console (undcemcs02.und.edu)
undcemcs02> emacs MyScanner.java   # Edit and create a file.

undcemcs02> ls                    # List directory contents.
MyScanner.java  

undcemcs02> cat MyScanner.java     # Concatenate files and print.

// Import the Scanner class.
import java.util.Scanner;
class MyScanner {
  public static void main( String[ ] args ) {
    // Create a Scanner object.
    Scanner myObj = new Scanner( System.in );
    System.out.print( "Enter username: " );
    // Read user input.
    String userName = myObj.nextLine( );
    // Output user input.
    System.out.println( "Username is: " + userName );
  }
}

undcemcs02> javac MyScanner.java    # Compile the program.

undcemcs02> ls                     # List directory contents.
MyScanner.java  MyScanner.class 

undcemcs02> java MyScanner          # Launch the Java application.
Enter username: Poke Mon
Username is: Poke Mon
 
undcemcs02>




      Every cloud has a silver lining.