Java Scanner reset()

Last updated by Utkarsh Sahu on Dec 27, 2024 at 06:28 PM
| Reading Time: 3 minutes

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>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

Last updated on: December 27, 2024
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Strange Tier-1 Neural “Power Patterns” Used By 20,013 FAANG Engineers To Ace Big Tech Interviews

100% Free — No credit card needed.

Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Ready to Enroll?

Get your enrollment process started by registering for a Pre-enrollment Webinar with one of our Founders.

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary