Java Scanner


Java ScannerViews 3561

The Java Scanner class is used to get user input from different streams like user input, file, and the input string. This class is part of the java.util package. By using various in-built methods, it can read different types of input.

Working of Scanner

The scanner object reads the input and divides it into tokens based on a delimiter which is normally white space. It then iterates through each token which is nothing but each data using its in-built methods. For example, consider the below input string

String s = "My age is 22";

In this case, it divides the string into 4 tokens “My”, “age”, “is”, “22” which uses space as a delimiter.

Create a Java Scanner object

Java Scanner - Java User Input

Import Scanner Java

To use the Java Scanner class, we import the java.util.Scanner package. The below code shows you how to create a scanner object with different input streams. The 1st object sc reads input data from user input which can be through the keyboard. The 2nd object sc1 reads input from a file and the 3rd object sc2 reads input from a string.

//Read from user input
Scanner sc = new Scanner(System.in);

//Read from file
Scanner sc1 = new Scanner(File f);

//Read from string
Scanner sc3 = new Scanner(String s);

Scanner Methods to read different input types

We can use the below methods to read different input types and other manipulations

MethodDescription
void close()Closes the scanner object
Pattern delimiter()Returns the Pattern of the scanner object that it currently uses to match delimiter
boolean hasNext()Returns true if there is another token in the input string. Returns a word
boolean hasNext(Pattern pattern)Returns true if the next token matches the pattern specified
boolean hasNextBigDecimal()Returns true if the next token has a BigDecimal
boolean HasNextBigInteger()Returns true if the next token has BigInteger
boolean hasNextBigInt()Returns true if the next token is BigInt
boolean HasNextBoolean()Returns true if the next token is boolean
boolean hasNextFloat()Returns true if the next token is Float
boolean hasNextDouble()Returns true if the next token is Double
boolean hasNextLine()Returns true if the scanner has another input line
String next()Finds and returns the next complete token in the input
BigDecimal nextBigDecimal()Returns the BigDecimal value from the input
BigInteger nextBigInteger()Returns the next BigInteger value from the input
Double nextDouble()Returns the next Double value from the input
Float nextFloat()Returns the next Float value from the input
Int nextInt()Returns the next int from the input
Long nextLong()Returns the next long value from the input
String nextLine()Returns the next line from the input string
Short nextShort()Returns the next short value from the input string

Java Scanner Exception

Java Scanner class throws the below exceptions while trying to read input:

  • IllelgalStateException – when we attempt to perform search operation on closed scanner object
  • NoSuchElementException – when there is no token found
  • InputMismatchException – when the input does not match with the expected type

Scanner nextLine() example using System.in

In the below example, we are creating a scanner object to read the Java user input using System.in which is nothing but the keyboard input. nextLine() method reads a single input line until it encounters “\n” (end of line).

import java.util.Scanner;
public class ScannerDemo1 {

  public static void main(String[] args) {
    System.out.println("Enter your name:");
    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    System.out.println("Your name is " + s);
    sc.close();
  }

}
Enter your name:
Ravi Kumar
Your name is Ravi Kumar

Java Scanner nextInt() example using System.in

Here, we use the nextInt() to read the integer value input from the user through keyboard input. Hence we pass System.in to the scanner object.

import java.util.Scanner;
public class ScannerDemo1 {

  public static void main(String[] args) {
    System.out.println("Enter your age:");
    Scanner sc = new Scanner(System.in);
    int i = sc.nextInt();
    System.out.println("Your age is " + i);
    sc.close();
  }

}
Enter your age:
35
Your age is 35

Java Scanner next() example using String input

In the below example, we use String as the input source. We pass this to the scanner object. To read individual words, we use the next() method. This method by default uses space as a delimiter. We use hasNext() method in a while loop so that it prints every word until it reaches the last word.

import java.util.Scanner;
public class ScannerString {

  public static void main(String[] args) {
    String s = "Welcome to Java Programming";
    Scanner sc = new Scanner(s);
    while(sc.hasNext()) {
      System.out.println(sc.next());
    }
    sc.close();
  }
}
Welcome
to
Java
Programming

Read input from a file

In this example, we use the file as an input source and pass this as a parameter to the java scanner object. We have created a file with contents having 2 lines. Hence using hasNextLine() in a while loop, we can read individual lines using the nextLine() till it reaches the last line.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerFile {

  public static void main(String[] args) throws FileNotFoundException {
    File f = new File(filepath); //Pass the filepath here
    Scanner sc = new Scanner(f);
    while(sc.hasNextLine()) {
      System.out.println(sc.nextLine());
    }
    sc.close();
  }

}
Welcome to Java programming
You will learn about Java Scanner class

Java Scanner example using a delimiter

When we pass a string as an input source to the scanner object, we can specify the delimiter to split the string instead of using the default space. In the below example, we use “-” as a delimiter.

import java.util.Scanner;
public class ScannerString {

  public static void main(String[] args) {
    //String s = "Welcome to Java Programming";
    String s = "This-is-an-example-of-using-delimiter";
    Scanner sc = new Scanner(s).useDelimiter("-");
    while(sc.hasNext()) {
      System.out.println(sc.next());
    }
  }
}
This
is
an
example
of
using
delimiter

 

Conclusion

In this tutorial, we have learned about Java scanner and how to read different input types using its built-in methods along with various examples.

Reference

Translate ยป