Scanner Class and Static Import with Example


java.util.Scanner class provides convenient methods to read data in the form of primitive type as well as string from the keyboard. A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
Constructor:
public Scanner(InputStream)
Methods:

public int nextInt() : Scans the next token of the input as an int.
public int nextFloat():Scans the next token of the input as Float
public int nextDouble():Scans the next token of the input as Double.
public String nextLine():Scans the next token of the input as String.
Simple Example:
import java.util.Scanner;
/**
 *
 * @author Navindra Jha
 */
public class Adder {
    public static void main(String as[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter First Number:");
        int num1 = sc.nextInt();
        System.out.println("Enter Second Number:");
        int num2 = sc.nextInt();
        int num3 = num1 + num2;
        System.out.println("Sum=" + num3);
    }
}

Static import

Provide the facility to import all the static members of a class and interface. Once imported they can be directly refer without any reference to the class or interface name.
Syntax: import static pkgName.ClassName.staticMember;
Or
Import static pkgName.ClassName.*;
Example:
import static java.lang.System.*;
/**
 *
 * @author Navindra Jha
 */
class HelloImport {

    public static void main(String as[]) {
       out.println("Hello Static import");
    }
}

No comments:

Post a Comment