User Input (Cont.)


Input Types
In the previous example, we used the nextLine() method, which is used to read String. To read other types, check the table on the right. In the example below, we use different methods to read data of various types:
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

MyScanner2.java (reading user input from the console)
import java.util.Scanner;
class MyScanner2 {
  public static void main( String[ ] args ) {
    Scanner myObj = new Scanner( System.in );
    System.out.print( "Enter name: " );
    // String input
    String name = myObj.nextLine( );
    // Numerical input
    System.out.print( "Enter age: " );
    int age = myObj.nextInt( );
    System.out.print( "Enter salary: " );
    double salary = myObj.nextDouble( );
    // Output input by user.
    System.out.println( "Name: "    + name );
    System.out.println( "Age: "     + age );
    System.out.println( "Salary: $" + salary + "K" );
  }
}
Console (undcemcs02.und.edu)
undcemcs02> emacs MyScanner2.java   # Edit and create a file.

undcemcs02> ls                     # List directory contents.
MyScanner2.java  

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

import java.util.Scanner;
class MyScanner2 {
  public static void main( String[ ] args ) {
    Scanner myObj = new Scanner( System.in );
    System.out.print( "Enter name: " );
    // String input
    String name = myObj.nextLine( );
    // Numerical input
    System.out.print( "Enter age: " );
    int age = myObj.nextInt( );
    System.out.print( "Enter salary: " );
    double salary = myObj.nextDouble( );
    // Output input by user.
    System.out.println( "Name: "   + name );
    System.out.println( "Age: "    + age );
    System.out.println( "Salary: $" + salary/1000 + "K" );
  }
}

undcemcs02> javac MyScanner2.java    # Compile the program.

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

undcemcs02> java MyScanner2          # Launch the Java application.
Enter name: Poke Mon
Enter age: 20
Enter salary: 70000
Name: Poke Mon
Age: 20
Salary: $70.0K
 
undcemcs02>




      The best revenge is massive success.