Reading Input Through Scanner Class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sreekandank
    New Member
    • Jun 2009
    • 45

    Reading Input Through Scanner Class

    Java provides the classes and methods that supports to read input and print output. To read the input, you first construct a Scanner that is attached to the standard input stream System.in.

    Scanner in=new Scanner(System. in);

    Methods of Scanner class:
    • nextLine() - to read a line of input
    • next() - to read a single word
    • nextInt() - to read an integer
    • nextDouble() - to read an double floating point number

    For example, the following code used to read a line of input:

    System.out.prin tln("Enter Your Name:");
    Scanner in=new Scanner(System. in);
    String name=in.nextLin e();

    ScannerDemo.jav a
    Code:
    import java.util.*;
    /**
     *@author Sreekandan.K
    */
    class ScannerDemo
    {
     public static void main(String args[])
     {
      Scanner in=new Scanner(System.in);
      System.out.println("What is ur name..?");
      String name=in.nextLine();
      System.out.println("What is ur age..?");
      int age=in.nextInt();
      System.out.println("Hello Mr."+name+",Your Age Is:"+age);
     }
    }
    Note: To be run this program in JDK1.5 or Higher version.
    Attached Files
    Last edited by MMcCarthy; Nov 6 '11, 08:42 AM. Reason: adding code tags
Working...