User Input from Keyboard

2.5 User Input from Keyboard

Accepting keyboard input in Java is done using a Scanner object.
Consider the following statement
Scanner console = new Scanner(System.in)
This statement declares a reference variable named console. The Scanner object is associated with standard input device (System.in).
To get input from keyboard, you can call methods of Scanner class. For example in following statment nextInt() method of Scanner takes an integer and returns to variable x :
int x = console.nextInt();
Some other useful methods of Scanner class
Method
Returns
int nextInt()
Returns the next token as an int.
float nextFloat()
Returns the next token as a float.
double nextDouble()
Returns the next token as a long.
String next()
Finds and returns the next complete token as a string ended by a blank.
String nextLine()
Returns the rest of the current line, excluding any line separator at the end.
Example 1 :
import java.util.Scanner;    // Needed for Scanner class

/**
 *  This program demonstrates keyboard input.
 */
public class RectangleArea
{
   public static void main(String[] args)
   {
      int length;    // To hold rectangle's length.
      int width;     // To hold rectangle's width.
      int area;      // To hold rectangle's area

      // Create a Scanner object to read input.
      Scanner console = new Scanner(System.in);

      // Get length from the user.
      System.out.print("Enter length ");
      length = console.nextInt();

      // Get width from the user.
      System.out.print("Enter width ");
      width = console.nextInt();

      // Calculate area.
      area = length * width;

      // Display area.
      System.out.println("The area of rectangle is " + area);
   }
}
Output :
Enter length 5
Enter width 8
The area of rectangle is 40

No comments:

Post a Comment

Pages