AppDividend
Latest Code Tutorials

Java Scanner Class Tutorial With Example | Scanner Class in Java

0

Java Scanner Class Tutorial With Example | Scanner Class in Java is today’s topic. Scanner class in java is present in java.util package. Java has various way to take input from the keyboard and java.uti.Scanner class is one of them. Java Scanner class breaks an input into the2e tokens using the delimiter which is considered as whitespace. It provides various methods to parse and read primitive values like int, float, sort, long, string, etc. If we want to use the Scanner class, create an object of the class and use any of the available methods found in a Scanner class documentation.

Java Scanner Class Tutorial

In Java, we can input with the help of the Scanner class. Java has several predefined classes which we can use. We will learn more about the classes later. The predefined classes are organized in the form of packages. Java Scanner class is found in the java.util package.

Java Scanner Class Declaration

See the following code.

public final class Scanner  
       extends Object  
       implements Iterator<String>

If we need to import a class or a package, add one of the following lines to the very beginning of your code.

import java.util.Scanner;   // This will import just the Scanner class
import java.util.*;   // This will import the entire java.util package

We can use either of the above lines. The first line only imports the Scanner class and the second line imports the whole java.util package.

After importing the class, we need to write the following statement in our program that will create an object of Scanner class.

Scanner s = new Scanner (System.in);

At this moment writing Scanner s, we are declaring s as an object of Scanner class. System.in within the round brackets tells Java that this will be System Input, i.e., input will be given to the system.

Example of Scanner Class in Java

See the below code example.

// Scan.java

import java.util.Scanner;

class Scan {
  public static void main(String[] ar) {
    // Declare the object and initialize with a predefined object which takes input
    // from keyboard

    Scanner sc = new Scanner(System.in);

    // String input
    System.out.println("Enter your Name:");
    String name = sc.nextLine();

    // Character input
    System.out.println("Enter your Gender:");
    char gender = sc.next().charAt(0); // it will take the first character of the entered word

    // Numerical data input
    // byte, short and float can be read
    System.out.println("Enter your Age:");
    int age = sc.nextInt();
    System.out.print("Enter your Phone Number:+91 ");
    long phoneNo = sc.nextLong();
    System.out.println("Enter your CGPA:");
    double CGPA = sc.nextDouble();

    // Printing all the values
    System.out.println("Name: " + name);
    System.out.println("Gender: " + gender);
    System.out.println("Age: " + age);
    System.out.println("Mobile Number: +91 " + phoneNo);
    System.out.println("CGPA: " + CGPA);
  }
}

See the below output.

Java Scanner Class Tutorial With Example

 

Key Points about Java Scanner Class

  1. If we want to create an object of Scanner class, we need to pass the System.in as an argument if we’re going to take input from the keyboard. If we’re going to receive input from a file, then we need to pass the file object of the class file.
  2. If we want to take input for the primitive type we have to write nextABC(); here ABC is a primitive type. For example, if we’re going to take input of short type, then we need to declare like nextShort().
  3. If we want to take input for string, we nextLine() is used.
  4. If we want to take input for the character, we have to use next().

Java Scanner Class Constructors

There are various types of the constructor are there which are used to Initialize or to take values. Now we are going to discuss some of the useful constructor one by one.

Scanner (File source)

Constructs the new scanner that produces values scanned from a specified file. If the source file is not found, a FileNotFoundException is thrown. Since it is a checked exception, it must be caught or forwarded by putting the phrase “throws FileNotFoundException” in the method header.

// ScannerConstructor.java

import java.io.*;
import java.util.Scanner;

class ScannerConstructorFile
{
    public static void main(String arg[]) throws Exception//catch exception
    {
        // Reading from a file
        Scanner sc = new Scanner(new File("FRUITS.txt")); 
        
        // Checking if sc has another token in the file
        while(sc.hasNext())
            System.out.println(sc.next());
        
    }
}

See the following code.

Scanner in Java

 

Scanner (InputStream source)

Constructs the new Scanner object that produces values scanned from a specified input stream.

Scanner (String source)

Constructs the new scanner object that produces values scanned from a specified string.

// ScannerConstructorString.java

import java.util.Scanner;

class ScannerConstructorString
{
    public static void main(String arg[])
    {
        String str = "AddDividend is the best e-learnig plateform for programer";
                
        Scanner sc = new Scanner(str);
        
        // checking if sc has another token in the string
        while(sc.hasNext())
            System.out.println(sc.next());
            
    }
}

The output is following.

Scanner (String source)

 

Scanner Class Various Methods

Now we’ll learn about various types of methods which belong to Scanner class.

delimiter()

The delimiter is the sequence of one or more characters used to specify the boundary between separate, independent regions in the plain text or other data streams. An example of the delimiter is the comma character, which acts as a field delimiter in a sequence of the comma.

Note: It can only be used Java 1.5 and above version

// Delimiter.java

//imprting scanner class
import java.util.Scanner;  

public class Delimiter
{  
      public static void main(String args[])
      { 
    	//Create Scanner object
 		Scanner scan = new Scanner("Hello World!");
		
 		//Printing the delimiter used
 		System.out.println("Delimiter used:"+scan.delimiter());
		
 		//Printing the Strings which is tokenized
		
 		while(scan.hasNext())
		{
 			System.out.println(scan.next());
 		}
    
        }  
}

The output is following.

delimiter() in Scanner class

 

close()

The close() method is used to close the Scanner class.

Syntax: public void close();

It takes no parameter and also doesn’t return any value.

// Close.java

import java.util.Scanner;    
public class Close
{    
   public static void main(String [] ar)
   {    
      String s = "Hello, everyone AppDividend welcomes you!";
	  
      //creating a scanner with the specified Object
      Scanner sc = new Scanner(s);
      System.out.println("" + sc.nextLine());
	  
      //closing the scanner  
      System.out.println("Scanner class is going to close...");  
      sc.close();
      System.out.println("Scanner Closed.");  
   }    
}

The output is following.

close() in Scanner class

 

toString()

The toString() method of Java Scanner class is used to get the string representation of Scanner object. The string representation of the Scanner contains the information which is useful for debugging purpose.

Some times we have to check if the next input is the specified type or it has ended (EOF is there).

If we want to check this, we have a general format(method) for all the primitive datatypes.

The format is: hasNextXYZ();  where primitive types are represented as XYZ, i.e., int, float, long,  boolean, etc.

If we have to find the next value is an int or not then the method will be like hasNextInt().

Similarly for String input we have method hasNextLine() and to check the first letter of any character we have hasNext.charAt(<Index number>)

// Check.java

import java.util.Scanner; 
  
 class Check 
{ 
    public static void main(String[] args) 
    { 
        //Declaring and initializing with Standard input
        Scanner sc = new Scanner(System.in); 
  
         
        int sum = 0, c = 0; 
		
		System.out.println("Eneter numbers:");
        // Cheking if an int value is available 
        while (sc.hasNextInt()) 
        { 
            // Read an int value 
            int num = sc.nextInt(); 
            sum += num; 
            c++;
        } 
        int mean = sum / c; 
        System.out.println("Mean: " + mean);
    } 
}

See the below output.

toString() in Scanner class

 

useDelimiter()

This method is used to set the delimiting pattern of the Scanner which is in use. We are going to discuss them one by one.

Syntax: public Scanner useDelimiter(Pattern pattern);

See the below code example.

useDelimiter() in Scanner Class

 

ioException()

The ioException() method of java.util.Scanner class returns the IOException last thrown by this Scanner’s underlying Readable.

Syntax: public IOException ioException()

It returns the last exceptions thrown by Scanner’s readable.

// IoExp.java

import java.util.*; 
  
public class IoExp 
{ 
    public static void main(String[] ar) throws Exception 
    { 
  
        String s = "AppDividend"; 
  
        // creating a new scanner with the specified String Object 
        Scanner sc = new Scanner(s);
  
        // printing string
        System.out.println("" + sc.nextLine()); 
  
        // check if there is an IO exception 
        System.out.println("" + sc.ioException()); 
  
        // close the scanner 
        sc.close(); 
    } 
}

See the below output.

ioException() in Scanner class

 

These were all about important methods and points of Scanner class.

Conclusively, Java Scanner Class Tutorial With Example | Scanner Class in Java is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.