Read interactive command-line input with Java

import java.io.*;

public class ReadString {

   public static void main (String[] args) {

      //  prompt the user to enter their name
      System.out.print("Enter your name: ");

      //  open up standard input
      BufferedReader br = new BufferedReader(new InputStreamReader
(System.in)); String userName = null; // read the username from the command-line; need to use
// try/catch with the // readLine() method try { userName = br.readLine(); } catch (IOException ioe) { System.out.println("IO error trying to read your name!"); System.exit(1); } System.out.println("Thanks for the name, " + userName); } }

 

we read the user’s input by passing the System.in object to the InputStreamReader and then into the BufferedReader The Java BufferedReader class gives us the readLine()method, and applies buffering to the input character input stream. Notice that the readLine() method can thrown an IOException error, so we have to enclose the statement in a try/catch statement.

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