How to use scanner class in java ?

Whenever you want interactivity in your program then you need to get input from the user. Most of the applications require input from user and with or without modification output is displayed to user. From version 1.5 java let’s you use scanner class to get input from user and you can easily show this output on the console.

The scanner class :

java.util.scanner

Creating scanner class object:

Scanner sc = new Scanner(System.in);

Methods of Scanner Object:

next()
nextInt()
nextDouble()
nextLine()

Using Scanner Class Objects and Methods:

First thing you need to do is create object of scanner class and specify system.in in the parenthesis. Read the code below:

Scanner sc= new Scanner(System.in);

Now depending on the type of data you need to retrieve from the user you need to use the respective method. The Scanner class is in java.util package so you need to import this if you wish to use scanner class.

Code Examples:

1. Creating Scanner Class Object

Scanner sc = new Scanner(System.in);

2. Read String Input from user

System.out.print(“Enter name”);
String name= sc.next();

3. Read Integer input from user

System.out.print(“Enter Number”);
String num = sc.nextInt();

4. Read Double value input from user

System.out.print(“Enter number”);
String number =sc.nextDouble();

When one of the next methods of scanner class are run, application waits for the user input. Once user enters input and hits enter program execution moves to next step.

Comments

  1. Bayag says:

    Tangina mo!

  2. shan says:

    thnx….