Keyboard Reading Java

To interact with a running program, that is to pass data for computation like user name, password or Employee particulars or Bank account credit and debit operations, two styles exist in a language like Java.

  1. Through Keyboard: It is very common input for practicing a language (but not in realtime). Again two types come here.
    1. Through command-line arguments: Command-line arguments are passed in Java that goes into args string array of main() method.
    2. Through keyboard: Like scanf() in C-lang. Again there are 3 ways in Java using three different classes.
      1. Using java.io.DataInputStream
      2. Using java.io.BufferedReader
      3. Using java.util.Scanner, mostly used and easier than the above other two. This tutorial illustrates this.
  2. Through GUI: Using text boxes and buttons and followed in realtime.
Following example illustrates Keyboard Reading Java using java,util.Scanner class.
import java.util.Scanner;                
public class StudentInput
{
 public static void main(String args[])
 {
   Scanner scan1 = new Scanner(System.in);   

   System.out.println("Enter Student Name:");     
   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);
 }
}

Keyboard Reading JavaOutput Screenshot on Keyboard Reading Java

Scanner scan1 = new Scanner(System.in);

Scanner is from java.util package but not from java.io. A Scanner object scan1 is created. The methods of Scanner class nextLine() returns a string, nextInt() returns an integer, nextDouble() returns a double value. Other methods also exist like nextFloat(), nextByte() returning a float and byte.

Learn more on Java: View All for Java Differences on 80 Topics

Leave a Comment

Your email address will not be published.