Skip to main content

Scanner in java

Scanner class

Java provide Scanner class to read input from keyboard.Scanner class is in java.util.Scanner package.

Use of Scanner Class

  •  To read input from keyboard

Steps to Read Input From User:

Step 1:

  • import java.util.Scanner;

Step 2:

  • Scanner sc1=new Scanner (System.in);

— System.in=represent standard input device

Step 3:

  • use methods to read inputs

Methods to read different types of value.

1)  nextInt()

  • It is used to read integer value from keyboard return type of this
    method is integer.

2)  nextDouble()

  • It is used to read double value from keyboard ,return of this
    method is double

3)  next()

  • It is  used to read string value from keyboard ,return of this
    method is string .

Program to take input from keyboard

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.Scanner;
 
class Pro11
{
    public static void main(String[] args)
 
     {
 
         Scanner sc=new Scanner(System.in);
 
        String stName;
        int stAge;
 
        System.out.println("Enter your Name: ");
        stName=sc.next();
 
        System.out.println("Enter Your age: ");
        stAge=sc.nextInt();
 
       if (stAge>18)
        {
 
                System.out.println("eligable for vote");
 
        }
 
       else 
       {
 
           System.out.println("not eligable!");
 
        }
     }
}
 
o/p:
Enter your Name:
VIVEK PATEL
Enter Your age:
22
eligible for vote