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

  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples

Trending

  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • Enforcing Architecture With ArchUnit in Java
  • Chat With Your Knowledge Base: A Hands-On Java and LangChain4j Guide
  1. DZone
  2. Data Engineering
  3. Data
  4. NetBeans in the Classroom: Console Input Using Scanners

NetBeans in the Classroom: Console Input Using Scanners

By 
Ken Fogel user avatar
Ken Fogel
·
May. 30, 14 · Interview
Likes (0)
Comment
Save
Tweet
Share
43.3K Views

Join the DZone community and get the full member experience.

Join For Free
ken fogel is the program coordinator and chairperson of the computer science technology program at dawson college in montreal, canada. he is also a program consultant to and part-time instructor in the computer institute of concordia university 's school of extended learning. he blogs at omniprogrammer.com and tweets @omniprof . his regular columns about netbeans in education are listed here .

i am old enough to remember commercial applications that had a console interface. my students have no experience with the console. when java was introduced the era of such applications was over. instead you used awt, then swing and now javafx. for the student starting out in programming these gui frameworks add complexity they may not be ready for. therefore i start my classes using console input and output.

input can be divided into two categories. the first is values. the primitive types such as int and double are value types. as i explain it, a value is a something you can perform both mathematical and logical operations on. the second is strings. a string does not have a value in the mathematical sense. instead it has a state. therefore it cannot be used in a mathematical expression. state can be compared and so strings can be used is logical expressions such as determining if two strings are the same. if you are ordering strings then you can also determine if one string is greater or less than the other.

java does not have any console input routines for values. to java everything you type is a string. this has meant that for many years every java textbook author provided a console input routine that could convert strings to values. java 1.5 made all these routines redundant with the introduction of the scanner class. i could now teach input without needing to go into detail about wrapper classes or the numberformatexception in a standard approach.
/**
 * ask the user for their weight
 */
public void inputweight() {
    scanner sc = new scanner(system.in);
    system.out.print("please enter your weight: ");
    int weight = sc.nextint();
    system.out.println("weight = " + weight);
}
there is a problem with this code. if the user enters a string that cannot be converted we get the numberformatexception we want to avoid.



scanner provides a solution with its ‘hasnext. . .’ methods. these methods determine if the user input can be converted to the target value. you can reject input and avoid the exception.

/**
 * ask the user for their weight
 */
public void inputweight() {
    scanner sc = new scanner(system.in);
    system.out.print("please enter your weight: ");
    int weight;
    // accept input and test to see if it’s an integer
    if (sc.hasnextint()) {
       // success, it was an integer so get it
       weight = sc.nextint();
       system.out.println("weight = " + weight);
    } else {
        // failure so retrieve the input as a string
        string bad = sc.next();
        // inform the user what went wrong
        system.out.println(bad + " cannot be converted to an integer");
    }
}
now when you run the program you get the following for a good input.



this is what you get for a bad input.



i will return to numeric input in another article as you do not want a program to end when the user makes one mistake.

character input

to make my assignments more interesting i have the students create a menu from which they must choose an action. i like to use letters as the menu choice.



the problem is that there is no nextchar() method in scanner. instead you need to use next() which will accept anything that you enter.

public void displaymenu() {
    scanner sc = new scanner(system.in);
    system.out.println("select an account");
    system.out.println("a: savings");
    system.out.println("b: checking");
    system.out.println("c: exit");
    system.out.print("please choose a, b or c: ");
    string choice = sc.next();
    system.out.println("you chose: " + choice);
}

which could result in the following:



the first improvement is to convert the string into a character. to do this the string must only be one character long. rather than checking the length you can just extract the first character in the string using the string class charat method.

 string choice = sc.next();
char letter = choice.charat(0);
system.out.println("you chose: " + letter);
this will work and if you enter “a” you will get ‘a’. the problem now is that the case of the character you entered should not matter. this is easy to solve by adding one more method from string into the mix.

 char letter = choice.touppercase().charat(0);
almost perfect but since we are using string input the user can enter any string they want. so “bacon” will result in ‘b’. we also need some way to control the allowable letters. in this menu the choices are a, b and c.

the solution is to use the ‘hasnext’ method for ‘next’. not the normal, no parameter version, but the version that takes a pattern. pattern is a polite way of saying regular expression.



from https://xkcd.com/208/

just as we did with integer input we first test the string that the user has entered. the regular expression will be the pattern that will be used to determine if the string is correct. this regular expression is probably the simplest one you can write. we want a single character, either upper or lower case and is one of the three allowable characters. here it is:

[abcabc]

the square brackets indicate that this is a character class expression that can match only a single character. what goes inside the brackets are the allowable characters, in this case a, b, c, a, b or c. since these characters are adjacent in the ascii/unicode table they can also be written as a range.

[a-ca-c]

putting this all together we get a routine that will only accept a single letter.

public void displaymenu() {
    scanner sc = new scanner(system.in);
    system.out.println("select an account");
    system.out.println("a: savings");
    system.out.println("b: checking");
    system.out.println("c: exit");
    system.out.print("please choose a, b or c: ");
    char letter;
    if (sc.hasnext("[a-ca-c]")) {
        string choice = sc.next();
        letter = choice.touppercase().charat(0);
        system.out.println("you chose: " + letter);
    } else {
        string choice = sc.next();
        system.out.println(choice + " is not valid input");
    }
}
now if you enter ‘a’:



but if you enter ‘aardvark’:



in my next article i will look at console input a bit more and i will introduce you to the beethoven test.
Console (video game CLI) Strings Data Types NetBeans Classroom (Apple)

Opinions expressed by DZone contributors are their own.

Related

  • DataWeave: Play With Dates (Part 1)
  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples

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: