Java Keyboard Input

For every language keyboard input is a must. That is, the user can feed data to a running Java program using keyboard. Java Keyboard Input involves I/O Streams.

In Java Keyboard Input can be taken in three ways using three different classes. Let us explore one and then see the other two. Here Scanner class is used which is easier to write code. Other two styles take extra lines of parsing.

Scanner is a class introduced with JDK 1.5. It is placed in java.util package to be nearer to Data Structures and not in package.

Following example on Java Keyboard Input takes from the Student name, circle radius and rectangle height and length.
import java.util.Scanner;                       // importing only one class
public class StudentInput
 public static void main(String args[])
   Scanner scan1 = new Scanner(;      // create Scanner object

   System.out.println("Enter Student Name:");   // start taking required inputs
   String stdName = scan1.nextLine();

   System.out.println("Enter Circle Radius as a whole number:");
   int radius = scan1.nextInt();

   System.out.println("Enter Recgtangle length, you can enter floating-point value:");
   double length = scan1.nextDouble();

   System.out.println("Enter Recgtangle height, you can enter floating-point value:");
   double height = scan1.nextDouble();
                                                // display the results of computation
   System.out.println("\nStudent Name:" + stdName);
   System.out.println("Circle Perimetetr: " + 2*Math.PI*radius);
   System.out.println("Rectangle Area: " + length*height);

Java Keyboard InputOutput Screenshot on Java Keyboard Input is connected OS stream passing from keyboard to CPU. Scanner object is connected to to read from keyboard. nextLine(), nestInt() and nextDouble() methods of Scanner class returns user input as a string, int and double that can be used in code directly for arithmetic calculations.

Three programs are given on Keyboard input using different classes and I/O Streams.

1. Keyboard Input – DataInputStream
2. Keyboard Input – Character Streams – BufferedReader
3. Keyboard Input – java.util.Scanner – No parsing

Leave a Comment

Your email address will not be published.