Sunday, August 1, 2010

Input or read in java from Standard IO

Lets first see what we mean by standard stream in java. Click here.

  1. Using scanner

    To read console input, you first construct a Scanner that is attached to the "standard input stream"
    Scanner in = new Scanner(;

    Now you use the various methods of the Scanner class to read input. For example, the nextLine method reads a line of input.

    System.out.print("What is your name? ");
    String name = in.nextLine();

    Here, we use the nextLine method because the input might contain spaces. To read a single word (delimited by whitespace), call

    String firstName =;

    To read an integer, use the nextInt method.

    System.out.print("How old are you? "); 
    int age = in.nextInt();

    Similarly, the nextdouble method reads the next floating-point number.

    Finally, add the line

    import java.util.*;

  2. Using JOptionPane

    String input = JOptionPane.showInputDialog(promptString)


    String name = JOptionPane.showInputDialog("What is your name?");

    Entering Integers
    String name = JOptionPane.showInputDialog("What is your age?");
    int age = Integer.parseInt(input);

    import javax.swing.*;

    Finally, whenever your program calls JOptionPane.showInputDialog, you need to end it with a call to System.exit(0). The reason is a bit technical. Showing a dialog box starts a new thread of control. When themain method exits, the new thread does not automatically terminate. Toend all threads, you call the System.exit method.

  3. Using BufferedReader Its most commonly used constructor is shown here:

    BufferedReader(Reader inputReader)
    Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to, use the following constructor:
    InputStreamReader(InputStream inputStream)

    So basic step is :

    InputStreamReader inp = new InputStreamReader(
    BufferedReader br = new BufferedReader(inp);

    Now to read character :

    char c =;

    To read String:

    String str = br.readLine();

    • Reading Characters
      int read( ) throws IOException
      Each time that read( ) is called, it reads a character from the input stream and returns it
      as an integer value. It returns –1 when the end of the stream is encountered. As you can
      see, it can throw an IOException.

      char c;
      BufferedReader br = new
      BufferedReader(new InputStreamReader(;
      c = (char);

    • Reading strings
      String readLine( ) throws IOException

      BufferedReader br = new BufferedReader(new
      String str;
      str = br.readLine();

No comments:

Post a Comment