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:
|
|
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. |