How to Read Data from the User | Heaton Research

How to Read Data from the User

Get the entire book!
Java for the Beginning Programmer

I will begin by showing you a simple program that will read data from the user. This program will only read the data from the user in text form. If you want to read data from the user in numeric form, you will have to first read the data as a string, and then convert it to numeric form. This technique will be discussed later in this chapter.

However, before we see how to input numbers, we will start with inputting strings. Inputting a string in Java is not as straightforward as you might think. Java provides no direct command to prompt for a line of text from the user. Because of this, some extra setup must be done, on our part, to enable Java to read lines of text from the user.

Java does not require too much additional code to read from the user. This additional code is the same for each program you write, so you will be able to copy the code, presented in Listing 4.1, to any program that needs to read lines of text from the console.

I will now show you an example program that reads lines of text from the user. This program will demonstrate what needs to be added to a Java program to read lines of text from the user. First, we will examine a simple program that prompts the user for their name, and then says “Hello” to that user. Listing 4.1 shows this program.

Listing 4.1: Read Data from the User (Hello.java)

import java.io.*;

public class Hello
{
  public static void main(String args[])
  {
    try
    {
      InputStreamReader inputStreamReader = 
        new InputStreamReader ( System.in );
      BufferedReader in = 
        new BufferedReader ( inputStreamReader );
      System.out.print("What is your name? ");
      String name = in.readLine();
      System.out.println("Hello " + name );
    }
    catch(IOException e)
    {
    }
  }
}

You will notice that it takes quite a few extra lines to actually accept input from the user. Most of them you do not need to be directly concerned with how they work. The line that actually reads the input is the first line below:

String name = in.readLine();
System.out.println(“Hello “ + name );

The above lines wait for a user to enter something and then press enter. What ever string the user enters will be placed into the string named “name”. Then, after the user enters their name, the program displays the word “Hello” followed by the user’s name.

Copyright 2005-2008 by Heaton Research, Inc.