What is Scanner class in Java? when was it introduced?


Until Java 1.5 to read data from the user programmers used to depend on the character stream classes and byte stream classes.

From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions.

By default, whitespace is considered as the delimiter (to break the data into tokens).

To read various datatypes from the source using the nextXXX() methods provided by this class namely, nextInt(), nextShort(), nextFloat(), nextLong(), nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(), nextFloat(), next().

Example − Reading data from keyboard

Following Java program reads name, date of birth, roll number and, percent from the user and prints back his age and grade. Here, we are using the methods of Scanner class to read the data.

Example

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.Date;
import java.util.Scanner;
public class ScannerExample {
   public static void main(String args[]) throws Exception {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.next();
      System.out.println("Enter your date of birth (dd-MM-yyyy): ");
      String dob = sc.next();
      System.out.println("Enter your roll number: ");
      int rollNumber = sc.nextInt();
      System.out.println("Enter your percentage: ");
      float percent = sc.nextFloat();
      //Getting Date object from given String
      Date date = new SimpleDateFormat("dd-MM-yyyy").parse(dob);
      LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
      //Calculating age
      Period period = Period.between(localDate, LocalDate.now());
      System.out.print("Hello "+name+" your current age is: ");
      System.out.print(period.getYears()+" years "+period.getMonths()+" and "+period.getDays()+" days");
      System.out.println();
      if(percent>=80){
         System.out.println("Your grade is: A");
      } else if(percent>=60 && percent<80) {
         System.out.println("Your grade is: B");
      }
      else if(percent>=40 && percent<60){
         System.out.println("Your grade is: C");
      } else {
         System.out.println("Your grade is: D");
      }
   }
}

Output

Enter your name:
Krishna
Enter your date of birth (dd-MM-yyyy):
26-09-1989
Enter your roll number:
1254
Enter your percentage:
83
Hello Krishna your current age is: 29 years 9 and 5 days
Your grade is: A

Updated on: 01-Aug-2019

314 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements