java-command-line-interactive-input-with-scanner-class-example

Read Interactive Command Line Input with Java Scanner Class

Introduction

Often while coding, we want command line input from user in interactive way. Then we use the input to execute the program in certain way. But how do we do it? There are several way of presenting choices to users in interactive manner. In this tutorial we learn to read interactive command line input with JAVA Scanner class. We can also use Console class introduced in JAVA 6. However, in this tutorial, we will focus on Scanner class.

 What is JAVA Scanner Class?

Scanner class was introduced as part of JAVA 5. This is one good way of addressing this problem of interactive user input from command line. As mentioned in the JAVA doc, it is — “A simple text scanner which can parse primitive types and strings using regular expressions.” However, it can also be doubled up to scan the user input from console in an interactive manner. Next, we’ll demonstrate the same using a simple demo code.

JAVA interactive command line input example

Here, we will write a small JAVA utility. Let’s consider that there are 2 jobs that this utility can accomplish –

  • Job number 1 (When user chooses 1 as the option)
  • Job number 2 (When user chooses 2 as the option)

If user presses 3, the program gracefully exits. If user makes any other choice, the utility smartly tells the user to make the write choice. Now, let’s look at the program below. I have documented the explanation in the program itself.

 

Run the program and see the result

Now, we will compile and run the program from command line. Let’s see what command line interaction looks like –

java-command-line-interactive-input-with-scanner-class-example

java-command-line-interactive-input-with-scanner-class-example

Conclusion

In this lite blog, we learnt to use JAVA Scanner class to read user input from command line in an interactive way. In the next one, I will demonstrate the same functionality using JAVA Console class. See you!! 🙂

114

No Responses

Write a response

This site uses Akismet to reduce spam. Learn how your comment data is processed.