About usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

Java Scanner reset()

Scanner reset in Java, as the name suggests, resets the scanner object. In many programming interview problems, we need to be comfortable with different ways to handle the input. Knowing about the functionalities that these methods provide can always come in handy. 

This article discusses the Scanner use cases in detail. We’ll also discuss:

  • What Is Scanner in Java?
  • How to Use the Scanner in Java?
  • Java Scanner reset() Method
  • Java Clear Scanner Using the nextLine() Method
  • How to Clear Scanner in Java?
  • Scanner API (Constructors and Methods) 
  • Interview Questions Related to Java Scanner
  • FAQ

What Is Scanner in Java?

Scanner is a class present in the java.util package. It breaks the input into tokens using a delimiter pattern, which by default is whitespace. These tokens can later be converted into values of different types using the various next methods. 

Example:

Input: Ronaldo has an extensive collection of 16 royal cars.

Here if we use space as a delimiter, below are the tokens that we get: 

[“Ronaldo”, “has”, “an”, “extensive”, “collection”, “of”, ”16”, “royal”, “cars”]

Now, we can convert these tokens into Integers or String based on the user requirements. So in our example, the token “Ronaldo” will be String, whereas the token “16” will be an Integer.

Scanner class breaks this input into tokens and provides methods like next(), nextLine(),  nextInt(), nextDouble(), etc to convert the tokens to String, Integer, Double etc respectively. So parsing the input in a given way becomes easy. Also, it enables us to provide our own delimiter to parse the input string.

How to Use the Scanner in Java?

There are various ways to read input using the Scanner class. Let's understand them one by one.

Use Hard-coded Input Strings

import java.util.Scanner;

public class Main {

   public static void main(String[] args) {

       String input = "Ronaldo has an extensive collection of 16 royal cars";

       Scanner scanner = new Scanner(input);

       while (scanner.hasNext()) {

           String token = scanner.next();

           if (token.matches("[0-9]+")) {

               System.out.println("\"" + token + "\" is a number");

           } else {

               System.out.println("\"" + token + "\" is a string");

           }

       }

      

       scanner.close();

   }

}

 

Output : 

"Ronaldo" is a string

"has" is a string

"an" is a string

"extensive" is a string

"collection" is a string

"of" is a string

"16" is a number

"royal" is a string

"cars" is a string

Explanation: 

Here, we have hardcoded the input in a String and passed it to a Scanner object. Finally, we read each of the tokens and check if it's a string or a number. The above program also shows that the default delimiter for Scanner is whitespace.

Use Hard-coded Input Strings Split by Custom Delimiters 

import java.util.Scanner;

 

public class Main {

 

    public static void main(String[] args) {

        String input = "Comma,separated,input,string";

        Scanner scanner = new Scanner(input);

        scanner.useDelimiter(",");

 

        while (scanner.hasNext()) {

            String token = scanner.next();

            System.out.println("Token - " + token );

        }

 

        scanner.close();

    }

}

Output : 

Token - Comma

Token - separated

Token - input

Token - string

Explanation: 

Here, we have hardcoded the input in a String and passed it to a Scanner object. Also, using the useDelimiter() function, we specify a comma as a delimiter. Then we read each of the tokens using the next() method. Also, as per the output, we can see that the input string splits based on commas.

<h3>Reading the Input From Console

 

import java.util.Scanner;

 

public class Main {

 

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

 

        String firstToken = scanner.next();

        String newLine = scanner.nextLine();

 

        System.out.println("Next String  - " + firstToken);

        System.out.println("Read Entire Line - " + newLine);

        scanner.close();

    }

}

 


Console Input: 

Hi This is a new Line

Console Output : 

Next String  - Hi

Read Entire Line -  This is a new Line

Explanation: 

Here, we read the input string from the console and then parse them. As evident from the output, the next() method in the Scanner class returns the next token, whereas you can use the nextLine() method to read the current line, excluding any line separator at the end.

<h3>Read Input From File 

You can also use Scanner along with FileReader to read input from a file. 

Syntax:

Scanner scanner = new Scanner(new FileReader("fullQualifiedFilePath"));

Code::

 

import java.util.Scanner;

 

public class Main {

 

    public static void main(String[] args) throws FileNotFoundException {

        Scanner scanner = new Scanner(new FileReader("fullyQualifiedFilePath"));

 

        String firstToken = scanner.next();

        String newLine = scanner.nextLine();

 

        System.out.println("Next String  - " + firstToken);

        System.out.println("Read Entire Line - " + newLine);

        scanner.close();

    }

}


Input: 

Here, we save our input in a file and pass the fullyQualifiedPath name as a parameter to the Scanner object. 

<h2>Java Scanner reset() Method

We use the reset method of java.util.Scanner to reset the Scanner object. Also, once we reset the scanner, it discards all the state information which has been changed by the invocation of useDelimiter(), useRadix(), and useLocale() methods. 

Code:

import java.util.Locale;

import java.util.Scanner;

 

public class Main {

 

    public static void main(String[] args) {

        String input = "This is a random input";

        Scanner scanner = new Scanner(input);

 

        //changing the delimiter, radix and locale.

        scanner.useDelimiter(",");

        scanner.useRadix(30);

        scanner.useLocale(Locale.FRANCE);

 

        System.out.println("Changed Delimiter = "+scanner.delimiter());

        System.out.println("Changed Radix = "+scanner.radix());

        System.out.println("Changed Locale = "+scanner.locale());

 

        // resetting the delimiter, radix and locale to defaults.

        scanner.reset();

 

        // default values of scanner delimiter, radix, and locale.

        System.out.println("Updated Delimiter = "+scanner.delimiter());

        System.out.println("Updated Radix = "+scanner.radix());

        System.out.println("Updated Locale = "+scanner.locale());

 

        scanner.close();

    }

}

Output : 

Changed Delimiter = ,

Changed Radix = 30

Changed Locale = fr_FR

Updated Delimiter = \p{javaWhitespace}+

Updated Radix = 10

Updated Locale = en_US

Explanation: 

As evident from the console output, although we had set the delimiter as comma, radix as 30, and locale as FRANCE, once the reset method of Scanner is invoked, it resets the value to default.

<h2>Java Clear Scanner Using the nextLine() Method

Using nextLine, we can skip the current line and move to the next line. 

Example:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int hexaDecimalNumber = 0;

        int radix = 16;

        while (hexaDecimalNumber == 0) {

            System.out.println("Please enter a valid number");

            // check if token is hexadecimal.

            if (scanner.hasNextInt(radix)) {

                hexaDecimalNumber = scanner.nextInt(radix);

            } else {

                System.out.println("Invalid Hexadecimal Number");

            }

            // skip current line and goto newLine to read input again.

            scanner.nextLine();

        }

        System.out.println("Hexadecimal Number = " + hexaDecimalNumber);

        scanner.close();

    }

}

Output : 

Please enter a valid number

Z

Invalid Hexadecimal Number

Please enter a valid number

A

Hexadecimal Number = 10

Explanation: 

The nextLine() method present in the Scanner class scans the current line. It then sets the Scanner to the next line to perform other operations on the new line, which helps us re-use the scanner object without destroying it or re-instantiating it.

<h2>How to Clear Scanner in Java?

To clear the Scanner object, we can re-instantiate the object again. We have a similar use-case as above; the only difference is instead of going to a new line, now we will re-initialize it.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int hexaDecimalNumber = 0;

        int radix = 16;

        while (hexaDecimalNumber == 0) {

            System.out.println("Please enter a valid number");

            // check if token is hexadecimal.

            if (scanner.hasNextInt(radix)) {

                hexaDecimalNumber = scanner.nextInt(radix);

            } else {

                System.out.println("Invalid Hexadecimal Number");

            }

            // re-initialize the scanner object.

            scanner = new Scanner(System.in);

        }

        System.out.println("Hexadecimal Number = " + hexaDecimalNumber);

        scanner.close();

    }

}

Output : 

Please enter a valid number

Z

Invalid Hexadecimal Number

Please enter a valid number

A

Hexadecimal Number = 10

<h2>Scanner API (Constructors and Methods) 

API

Usecases.

nextInt()

Scans the next token as an Integer.

nextFloat()

Scans the next token as an Float.

nextBigInteger()

Scans the next token as an BigInteger.

nextDouble()

Scans the next token as a Double.

nextLine()

Scans past the current line and returns skipped input.

next()

Scans and returns the next token.

reset()

Resets the Scanner delimiter, radix, locale to default.

close()

Closes the Scanner.

<h2>Coding Interview Questions Related to Java Scanner

  • Read an input string separated by numbers and chars. You have two strings that contain decimal values, but the strings are too large to be converted to double. Add the strings and return the result.

<h2>Java Scanner reset FAQS

Question 1: Is the performance of the Scanner class better as compared to the BufferedReader class? 

The Scanner class is significantly slower in performance as compared to BufferedReader class.

Question 2: Can the Scanner class be used along with FileReader class in Java?

Yes, FileReader class can be passed as a parameter to the Scanner constructor. 

<h2>Are You Ready to Nail Your Next Coding Interview?

Whether you’re a Coding Engineer gunning for Software Developer or Software Engineer roles, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of Software Engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

————

Article contributed by Problem Setters Official


Attend our Free Webinar on How to Nail Your Next Technical Interview

Recommended Posts

All Posts