Tuesday, February 21, 2012

How to read input from user in java program

Here is the sample demo to get inputs from user in java program while running in command prompt.

I am providing you a java application that will communicate with the user at the command line and returns the user input.

I have prompt the user to enter the name by using System.out.print() method to keep the cursor on the same line. Then I have used the System.in object, along with the InputstreamReader and BufferedReader class in order to read the user input. The br.readline() method reads the name from command line.
After pressing the enter key, you will get the user input.

Here is the sample example java code:

import java.io.*;

public class ReadInputFromUser
{
    public static void main (String[] args) 
    {
       System.out.print("Enter your name and press Enter: ");
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       String name = null;
       try
       {
         name = br.readLine();
       }
       catch (IOException e) 
       {
         System.out.println("Error!");
         System.exit(1);
       }
       System.out.println("Your name is " + name);
    }
}