Wednesday 27 April 2016

SCANNER CLASS IN JAVA


Scanner Class in Java



Scanner  is a class in java.util package used for obtaining the input of the primitive types like int,double etc. and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming.
  • To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.
  • To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort()
  • To read strings, we use nextLine().
  • To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) funtion returns the first character in that string.

  • EXAMPLE:-.
// Java program to read data of various types using Scanner class.
import java.util.Scanner;
public class ScannerDemo1
{
    public static void main(String[] args)
    {
          
// Declare the object and initialize with
        
        Scanner sc = new Scanner(System.in);
         // String input
        String name = sc.nextLine();
         // Character input
        char male = sc.next().charAt(0);
         // Numerical data input
         // byte, short and float can be read
         // using similar-named functions.
        int age = sc.nextInt();
        long landline_no = sc.nextLong();
        double percentage= sc.nextDouble();
         // Print the values to check if input was correctly obtained.
        System.out.println("Name: "+name);
        System.out.println(" male: "+male);
        System.out.println("Age: "+age);
        System.out.println("landline_no: "+landline_no);
        System.out.println("PERCENTAGE: "+PERCENTAGE);
    }
}

No comments:

Post a Comment