Various methods or types to read input from Console (keyboard) in Java


The below Java program illustrates the types or methods that we can receive inputs from a user

import java.util.Scanner;
import java.io.*;
class ConsoleReadingDemo {
static String name;
    public static void main(String[] args) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print(“Please enter user name : “);
        
        try {
            name = reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(“You entered : ” + name);

        // ===== In Java 5, Java.util,Scanner is used for this purpose.
        Scanner in = new Scanner(System.in);
        System.out.print(“Please enter user name : “);
        name = in.nextLine();      
        System.out.println(“You entered : ” + name);
 
 
        // ====== This feature from Java 6
        Console console = System.console();
        name= console.readLine(“Please enter user name : “);   
        System.out.println(“You entered : ” + name);

    }
}

Thank you for reading

About pacesettergraam

A good and realistic person

Posted on January 19, 2013, in Java and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: