Getting input from keyboard

Sang Shin, sang.shin@sun.com, www.javapassion.com/javaintro


In this lab, you are going to build a simple interactive Java application, which gets user entered input data from keyboard.  You are going to read date from both command line and through a dialog box.


Expected duration: 90 minutes


Software Needed

Before you begin, you need to install the following software on your computer.


Change Log



Lab Exercises


Exercise 1: Getting input from keyboard via BufferedReader class

In this exercise, you are going to build a simple interactive Java application, which gets user entered input data from keyboard. The program will use BufferedReader and InputStreamReader classes to receive the intput data. (You don't really need to understand in detail how these classes work, however.)  You will also learn how to use Javadoc to get more information on Java classes.

(1.1) Build and run GetInputFromKeyboard Java program

1. Create a NetBeans project



Figure-1.10: Create MyGetInputFromKeyboardProject
2. Modify the IDE generated GetInputFromKeyboard.java  as shown in Code-1.11 below. Study the code by paying special attention to the bold-fonted comments.  For now, don't worry about the details of the BufferedReader and InputStreamReader classes for now.
/*
 * GetInputFromKeyboard.java
 *
 * Created on January 20, 2007, 6:22 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author sang
 */
public class GetInputFromKeyboard {
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
        // Create BufferedReader object from Standard input device.
        // Standard input device is typically a keyborad.
        BufferedReader dataIn = new BufferedReader(new
                InputStreamReader( System.in) );
       
        // Prompt a user to enter his/her name
        String name = "";
        System.out.println("Please Enter Your Name:");
       
        // Read data into name variable
        try{
            name = dataIn.readLine();
        }catch( IOException e ){
            System.out.println("Error!");
        }
       
        // Display the name
        System.out.println("Hello " + name +"!");
    }
   
}
Code-1.11: GetInputFromKeyboard.java

3. Build and run the program

Figure-1.12: Enter value
Please Enter Your Name:
Sang Shin
Hello Sang Shin!
Figure-1.13: Result


Figure-1.14: Display the data that was entered

4. Modify the GetInputFromKeyboard.java to read your age as shown in Code-1.15 below. The code fragment that needs to be added is highlighted in bold and blue-colored font.

/*
 * GetInputFromKeyboard.java
 *
 * Created on January 20, 2007, 6:22 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author sang
 */

public class GetInputFromKeyboard {
   
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
        // Create BufferedReader object from Standard input device.
        // Standard input device is typically a keyboard.
        BufferedReader dataIn = new BufferedReader(new
                InputStreamReader( System.in) );
       
        // Prompt a user to enter his/her name
        String name = "";
        System.out.println("Please Enter Your Name:");
       
        // Read entered data into name variable
        try{
            name = dataIn.readLine();
        }catch( IOException e ){
            System.out.println("Error!");
        }
       
        // Display the name
        System.out.println("Hello " + name +"!");
       
        // Prompt a user to enter his/her age
        String age= "";
        System.out.println("Please Enter Your Age:");
       
        // Read entered data into age variable
        try{
            age = dataIn.readLine();
        }catch( IOException e ){
            System.out.println("Error!");
        }
       
        // Display the name and age
        System.out.println("Hello " + name +"!" + " " + "Your age is " + age);
    }
   
}
Code-1.15: Add code to prompt a user to enter age

5. Build and run the program
Please Enter Your Name:
Sang Shin
Hello Sang Shin!
Please Enter Your Age:
100
Hello Sang Shin! Your age is 100
Figure-1.16: Display of name and age

                                                                                                                        return to top of the exercise


(1.2) Convert user entered "String" type value to "int" type value


Now suppose you want to add the following logic to the program.

If the entered age is over 100, display
    Hello <name>, you are old!
Otherwise
    Hello <name>, you are young!

Notice in the previous code, your program received the age in the form of String type.  And you cannot compare String type "99" with int primitive type of 100.  In other words, you have to convert the String type of "99" to int type of 99 before you compare it against another int type 100.

Fortunately, there is a method called parseInt() in the Integer class for converting String type into int type. 

1. See the JavaDoc of Integer class.

Figure-1.20: Javadoc of Integer class

Figure-1.21: Javadoc of the parseInt(String s) method

Figure-1.22: Detail information on parseInt(String s) method

2. Modify the GetInputFromKeyboard.java to read your age as shown in Code-1.23 below. The code fragment that needs to be added is highlighted in bold and blue-colored font.

/*
 * GetInputFromKeyboard.java
 *
 * Created on January 20, 2007, 6:22 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 * @author sang
 */
public class GetInputFromKeyboard {
   
    /** Creates a new instance of GetInputFromKeyboard */
    public GetInputFromKeyboard() {
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
        // Create BufferedReader object from Standard input device.
        // Standard input device is typically a keyboard.
        BufferedReader dataIn = new BufferedReader(new
                InputStreamReader( System.in) );
       
        // Prompt a user to enter his/her name
        String name = "";
        System.out.println("Please Enter Your Name:");
       
        // Read entered data into name variable
        try{
            name = dataIn.readLine();
        }catch( IOException e ){
            System.out.println("Error!");
        }
       
        // Display the name
        System.out.println("Hello " + name +"!");
       
        // Prompt a user to enter his/her age
        String age= "";
        System.out.println("Please Enter Your Age:");
       
        // Read entered data into age variable
        try{
            age = dataIn.readLine();
        }catch( IOException e ){
            System.out.println("Error!");
        }
       
        // Display the name and age
        System.out.println("Hello " + name +"!" + " " + "Your age is " + age);
       
        // Convert the String type of age variable into int primitive type variable ageint.
        int ageint = Integer.parseInt(age);
       
        // Now you can compare the int primitive type against int type value 100
        if (ageint > 100){
            System.out.println("Hello " + name +"!" + " " + "You are old.");
        } else{
            System.out.println("Hello " + name +"!" + " " + "You are young.");
        }
    }
   
}
Code-1.23: Modified GetInputFromKeyboard.java

5. Build and run the program
Please Enter Your Name:
Sang Shin
Hello Sang Shin!
Please Enter Your Age:
23
Hello Sang Shin! Your age is 23
Hello Sang Shin! You are young.
Figure-1.24: Result of running the application

                                                                                                                        return to top of the exercise


(1.3)  Display Javadoc in a context-senstive manner within NetBeans IDE


In this exercise, you are going to see the Javadoc of the Integer class in a context senstive fashion.  Before taking this step, please make sure you've download the Java Standard Development Kit (JDK™) version 6.0 Documentation zip file (download) into a directory of your choice.

1. Add J2SE Development Kit Documentation 6.0 zip file to the NetBeans.

Figure-1.31: Open Java Platform Manager

Figure-1.32: Add Javadoc file

Figure-1.33:  Select jdk-6-doc.zip file

Figure-1.34: jdk-1_5_0-doc.zip file is added

2. Perform context-sensitive Javadoc.

Figure-1.35: Show Javadoc on Integer

Figure-1.36: Javadoc of Integer class

Summary

In this exercise, you learned how to read data entered through a standard input device, keyboard.  You also learned how to use online version of Java documentation and how to display Javadoc of a class through context-senstive manner.
   
                                                                                                                                   Return to the top


Exercise 2: Getting input from keyboard via JOptionPane

In this exercise, you are going to build the same application you built in Exercise 1 but this time using JOptionPane class. 

  1. Build and run a Java program that uses conditional operators

(2.1) Build and run a Java program that uses conditional operators

1. Create a NetBeans project

2. Modify the IDE generated InputFromKeyboardJOptionPane.java.
import javax.swing.JOptionPane;
/*
 * InputFromKeyboardJOptionPane.java
 *
 * Created on January 24, 2007, 10:46 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author sang
 */
public class InputFromKeyboardJOptionPane {
   
    /** Creates a new instance of InputFromKeyboardJOptionPane */
    public InputFromKeyboardJOptionPane() {
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        String name = "";
        name=JOptionPane.showInputDialog("Please enter your name");
        String msg = "Hello " + name + "!";
        JOptionPane.showMessageDialog(null, msg);
    }
   
}
Code-2.21: Modified InputFromKeyboardJOptionPane.java

3. Build and run the program


Figure-2.22: Enter name


Figure-2.23: Message is displayed


Summary

In this exercise, you are going to build the same application you built in Exercise 1 but this time using JOptionPane class. 

                                                                                                                        return to the top



Homework exercise (for people who are taking Sang Shin's "Java Programming online course")


1. The homework is to modify the MyInputFromKeyboardJOptionPaneProject project above.   (You might want to create a new project by copying the MyGetInputFromKeyboardJOptionPaneProject project.)  You can name the new project in any way you want but here I am going to call to call it as MyGetInputFromKeyboardJOptionPaneProject2
2. Send the following files to javaprogramminghomework@sun.com with Subject as JavaIntro-javainputkey.