How to reset a Scanner in Java

How to reset a Scanner in Java:

Scanner is an important class in Java. By using this class, you can parse primitive types and strings.

Scanner class provides one method called reset that can be used to remove its state information. In this post, we will learn how to use this method and what reset() method actually does.

Definition of reset():

reset() method is defined as below:

public Scanner reset()

It is a method defined in the Scanner class and it is public. It resets the scanner.

It resets the data those are set by the below three methods:

public Scanner useDelimiter(String pattern):

This method changes the scanner’s delimiting pattern. We can use this method and pass one new string for the new delimiting pattern.

reset() resets the delimiting pattern defined by this method to default.

public Scanner useLocale(Locale locale):

This method is used to change the locale of the scanner. It takes one locale as the parameter and changes the scanner’s locale to this locale.

reset() resets the locale to the default locale.

public Scanner useRadix(int radix):

It changes the scanner’s default radix to any other value. reset() method resets this value to 10.

So, we can use reset() to reset the values set by these three methods. It is similar to:

scanner.useDelimiter("\\p{javaWhitespace}+")
          .useLocale(Locale.getDefault())
          .useRadix(10);

Let’s try this with an example.

Java program of scanner reset():

package com.company;

import java.util.Locale;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        sc.useRadix(30);
        sc.useLocale(Locale.FRANCE);
        sc.useDelimiter("$");

        System.out.println("Enter a string : ");
        String s = sc.nextLine();

        System.out.println(s);

        System.out.println("Scanner radix: "+sc.radix()+", locale: "+sc.locale()+", delimiter: "+sc.delimiter());
        sc.reset();
        System.out.println("After reset, Scanner radix: "+sc.radix()+", locale: "+sc.locale()+", delimiter: "+sc.delimiter());
    }
}

For the above example,

  • We are changing the radix, locale and delimiter of the Scanner before calling reset.
  • We are printing these values before and after reset() is called.

If you run this program, it will print output as like below:

Enter a string :
Hello World
Hello World
Scanner radix: 30, locale: fr_FR, delimiter: $
After reset, Scanner radix: 10, locale: en_IN, delimiter: \p{javaWhitespace}+

java scanner reset

You might also like: