Search code examples
javainputjava.util.scanneruser-input

What does the reset() method of Scanner do?


I have a simple Java program using java.util.Scanner as follows:

package com.company;

import java.io.IOException;
import java.util.Scanner;

public class Favorite_Number {
    public static void main(String[] args) throws IOException {
        int X,sum = 0,rem = 0,t;
        Scanner s = new Scanner(System.in);
        t = s.nextInt();
        while(t!=0) {
            s.reset();  // <-- what does it do?
            X = s.nextInt();
            while (X > 0) {
                rem = X % 10;
                if (rem == 5) {
                    sum++;
                }
                X = X / 10;
            }
            System.out.println(sum);
            sum = 0;
            t--;
        }

    }
}

What does s.reset() do? If I remove it, the program still works fine.


Solution

  • reset() is explained here with examples

    and as per documents purpose stated as:

    On resetting a scanner discards all of its explicit state information which may have been changed by invocations of useDelimiter(java.util.regex.Pattern), useLocale(java.util.Locale), or useRadix(int).

    Docs reference: https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#reset--