Scanner Input

April 11, 2016, by Hamid Siddiqui

/**
 * @author Hamid Siddiqui
 * https://github.com/inventionsbyhamid
 * https://www.quora.com/profile/Hamid-Siddiqui
 *
 * @program To use Scanner class for taking input from user
 *
 * While using Scanner we should import java.util.Scanner class.
 * Scanner IO is slow and is not recommended to use in real applications where large input is required.
 */

import java.util.Scanner;

class ScannerInput {

    public static void main(String args[]) {

        //create Scanner object named k, name can be anything
        Scanner k = new Scanner(System.in);

        System.out.println("Enter string");
        //input String
        String s = k.nextLine();
        System.out.println("String = " + s);

        System.out.println("Enter integer");
        //input int, k.readLine() takes input as String as above, Integer.parseInt() converts the string to int
        int n = k.nextInt();
        System.out.println("int = " + n );

        System.out.println("Enter integer");
        //input long
        long l = k.nextLong();
        System.out.println("long = " + l);

        System.out.println("Enter decimal number");
        //input double
        double d = k.nextDouble();
        System.out.println("double = " + d);

        System.out.println("Enter decimal number");
        //input float
        float f = k.nextFloat();
        System.out.println("float = " + f);

        System.out.println("Enter string");
        //input just one string with no spaces
        s = k.next();
        System.out.println("String = " + s);


    }
}
Sample Input/Output

Enter string
My name is Hamid
String = My name is Hamid
Enter integer
37895
int = 37895
Enter integer
4678234
long = 4678234
Enter decimal number
34.654
double = 34.654
Enter decimal number
45.762
float = 45.762
Enter string
My name is User
String = My




Sum →

← Buffered Reader Input