DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Merge HTML Documents in Java
  • The Future of Java and AI: Coding in 2025
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Using Python Libraries in Java

Trending

  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  • Secure by Design: Modernizing Authentication With Centralized Access and Adaptive Signals
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • The Smart Way to Talk to Your Database: Why Hybrid API + NL2SQL Wins
  1. DZone
  2. Coding
  3. Java
  4. If You're Using Java’s Scanner Class for Keyboard Input, You're Doing it Wrong

If You're Using Java’s Scanner Class for Keyboard Input, You're Doing it Wrong

So, if you're using the Scanner class for keyboard input in Java, you're probably doing it wrong. Check out this post to learn more about the Scanner class.

By 
Ken Fogel user avatar
Ken Fogel
·
Updated Sep. 04, 18 · Opinion
Likes (52)
Comment
Save
Tweet
Share
57.9K Views

Join the DZone community and get the full member experience.

Join For Free

Yesterday, I gave my third-year Java students a warm-up exercise. The students were free to use console, Swing, or JavaFX for user input. Most chose a console because they had minimal exposure to GUI coding and that is one of the main topics covered in my course. Within a few minutes, some hands went up in regards to using the Scanner class. Here is a simplified version of what they were trying to do:

public class App {

    public void perform() {
        firstScanner();
        secondScanner();
    }

    public void firstScanner() {
        String str = "";
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string: ");
        if (sc.hasNext()) {
            str = sc.next();
            sc.nextLine();
        }
        sc.close();
        System.out.println("str = " + str);
    }

    public void secondScanner() {
        int num = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number: ");
        if (sc.hasNextInt()) {
            num = sc.nextInt();
            sc.nextLine();
        }
        sc.close();
        System.out.println("num = " + num);
    }

    public static void main(String[] args) {
        App app = new App();
        app.perform();
        System.exit(0);
    }
}

Scanner Demo

When this program executes, it asks for the first String but never asks for the int . A run looks like:

Enter a string: 
bob
str = bob
Enter a number: 
num = 0


It never stops to ask for the number and immediately prints out the default value for num. I had never seen this problem before. When I teach an introductory course, I show my students that the Scanner for keyboard input should, in most cases, be a class variable initialized in the constructor. I also must admit that I never close the Scanner object when the keyboard is involved.

You can see that, in the code, the Scanner object is closed in each method. I didn’t think this was a problem, and so I stared at the student’s code for a few minutes and then went to Google. There was not much to be found. Most of the information showed that when using Scanner to access a file, you should close it. Most articles that used Scanner for keyboard input declared the Scanner in a method and closed it at the end of the method. There was one suggestion in a StackOverflow posting that suggested a potential problem with closing Scanner for keyboard input, but it was not definitive.

My next experiment was to remove the close() statements. The Scanner performed as originally expected:

Enter a string: 
bob
str = bob
Enter a number: 
23
num = 23


So, back to research on Google where I uncovered a fact not mentioned in any JavaDocs or in any article from any source when discussing the Scanner class. If  System.in, a BufferedInputStream from the keyboard, is closed, as happens when the Scanner object is closed, you are closing a System stream that cannot be re-opened. The program must be exited and then re-run to re-establish  System.in.

I thought this was strange and looked deeper into how the keyboard was connected to System.in. This stream is established by private methods in the JVM. I did see suggestions as to how this could be re-established, but I suspect that this code may have never been tested:

Suggestion #1

FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
System.setIn(new BufferedInputStream(fdIn));


Suggestion #2

System.setIn(new FileInputStream(FileDescriptor.in));



Neither worked to re-establish the connection between System.in and the keyboard. If you know a way, then I’d dearly like to know. For now:

DO NOT CLOSE A SCANNER OBJECT INITIALIZED WITH  System.in!

Java (programming language)

Published at DZone with permission of Ken Fogel, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Merge HTML Documents in Java
  • The Future of Java and AI: Coding in 2025
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Using Python Libraries in Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: