Java Scanner class | Java Scanner demo program

Scanner Class In Java:

Scanner class is used to collect user input. To create an object of Scanner class first we need to import java.util.Scanner class and we need to pass predefined object System.in.

  •  To read the values of certain data types, Syntax is: nextDatatype() 

For Example: 
1. To read numerical value use nextShort() or nextInt() methods(depends on your requirement).
2. To read Strings, use nextLine() function.
3. To read a single character we need to use next().charAt(0). Here next() returns next token in the input as a String and charAt(0) function will return the first character in that String. 
4. Same as above to read floating point values use nextFloat() or nextDouble() functions.

Ex: 

Write java program to accept input from user and print it on the output screen. Java Scanner demo program :

import java.util.Scanner;/*util.Scanner is a class which is used to get input from user*/

    class Main {
        public static void main(String args[])
        {
            Scanner sc = new Scanner(System.in);/*It will create a new object of type Scanner*/

            System.out.println("Enter your name: ");
            String str = sc.nextLine();/*It Scans the next token of the input as a string till the end of line */
            System.out.println("Enter your age: ");
            int num = sc.nextInt();/*It Scans the next token of the input as a int */

            System.out.println("Your name is: "+str);
            System.out.println("Your age is: "+num);
        }
}

Above java program shows the following output:

Enter your name: Omkar Lokhande
Enter your age: 20

Your name is: Omkar Lokhande
Your age is: 20

No comments:

Post a Comment

If you have any doubts, please discuss here...👇