Input Mechanism - Scanner Class
CSE 110 Principles of Programming with Java
Spring 2021
This document is meant to be used as a supplement to a text book. This document takes a look at how to use the
Scanner class in JAVA to acquire user input. The examples used in this document are referenced from various textbooks
and online resources. It is advisable to use a text book for a deeper understanding of each concept and for more examples.
1 User Input
In the past few lectures we have taken a look at how to declare and define variables of various datatypes. However, for each
of those examples, it was we, the programmer, who always set the value of those variables. In real world scenarios, more
often than not, user input is required prior to doing any of the assigned tasks. For example consider a simple calculator.
You need to give the numbers to the calculator and assign the operation of choice and only then will it compute the result
for you. In this case, the numbers and operation are both said to be given by the user (user input). If we were to conside
this simple calculator as a JAVA program, then we would need some mechanism or programming construct that allows us
to take inputs from the user. JAVA has multiple pre-defined classes that programmers can take advantage of and get input
from the user. User input can be acquired in the form of keyboard input, mouse movement and so on. In this course, we will
mainly be focussing on acquiring the data (letters and numbers) that user types on their keyboard.
2 Scanner Class
For the duration of this semester, the JAVA class that we will be leveraging to acquire input from the user is called the
Scanner class. It is located within the util package and contains methods and variables (linked to the input stream) which
facilitate acquiring data or input from the user. Since the Scanner class is located in a package that is separate from the
one in which we write our source code it must be imported inside our source code file prior to using it in our own code. The
purpose of importing a class ( or classes or an entire package) within our source file is to be able to access the variables and
methods inside those classes. Packages and importing them are topics that we will take a closer look at once we cover class
and objects later in the semester. For now please think of them as black box constructs that when given an input provide
you with your desired output. In this case, the Scanner class and associated objects are black boxes that allow us to tap in
to the input stream and acquire user input.
To use the Scanner class to get user input in our program we need to create objects of that class. Since we are just starting
out learning how to program in JAVA, we will not dive into the depths of object creation. Instead we will treat objects as
just another variable whose datatype is the class we are dealing with and whose value will always be predefined by a set of
keywords. Objects of classes are in fact variables as well and their datatype is the associated class (remember that classes
are examples of referenced/derived datatypes). We will be going into the details of classes and objects later in the semester.
In this case, the Scanner class is the one whose objects we are interested in. Creating an object is very similar to declaring a
variable of a particular datatype - you need to use the co
ect datatype (in this case the Scanner class) and then give a name
for the object of your choice. When you want to define what the object’s initial value will be, we use the new operator and
then a few keywords (that will be made known to you).
classname objectname = new classname(optional parameters);
With this general syntax in mind, let us try to create an object of the Scanner class called sc . Note here that similar to
naming of variables, you can assign object names of your choice. However, ensure that they are relevant names to prevent
any confusion while coding. We decided to use the name sc since it looks like an a
eviated form the word Scanner and
also because it is shorter and therefore easier to type (we will be using this variable a lot in our code so we wanted a name
that is relevant and easy to type).
Scanner sc;
Now we have declared a Scanner object called sc . We can now define this object with a value that will allow us to tap into
the input stream which is required for getting user input. To do so use the following line -
sc = new Scanner(System.in);
You can either declare and define Scanner objects in two separate lines OR you can do it in one line as shown below.
Scanner sc = new Scanner(System.in);
The keywords that were assigned to the Scanner class object sc do two things - firstly, the new keyword will instantiate
the object of the class. Secondly, the argument to the function System.in will allow the newly created object sc to access the
input stream. We just used a whole lot of words that may not make too much sense for now, but we will come back to this
when we deal with classes and objects. For now, let us simply try to understand how to create Scanner class objects and
what keywords are needed to do so. Now that we have learnt a little about the Scanner class and how to use it to create
an object that can take inputs from the user, we need to learn what kind of inputs can we obtain.
• nextInt() :- Used to read the next token as an integer value
• nextByte() :- Used to read the next token as a byte integer value
• nextShort() :- Used to read the next token as a short integer value
• nextLong() :- Used to read the next token as a long integer value
1
• nextDouble() :- Used to read the next token as a double value
• nextFloat() :- Used to read the next token as a float value
• nextLine() :- Used to read the next token as a string value
• close() :- Used to close the input stream linked to our Scanner object
The Scanner class allows us to handle inputs of almost all the primitive datatypes. When the user enters some input it is
always of datatype String. However, data needed for computations and such must either be integers or real numbers (floating
point). So the user input strings must be converted to the co
ect datatype prior to being assigned to the associated variables.
Thankfully the Scanner class has methods that automatically do this conversion for us and make our coding time simpler.
The methods that we will be using the most throughout the course are listed below along with the type of inputs they can
handle.
To use any of the listed methods while taking in input from the user, we need to associate the co
ect datatype related to that
input. For example, if we wanted to read an integer input from the user we would use the nextInt() method with our Scanne
object. Similarly if we wanted to read a string from the user we would use the nextLine() method with our Scanner object.
Having learnt how to user Scanner class objects and methods to get inputs from the user, let us try to accept a floating
point number from the user. Now before we do so, we need to understand that the user input must be stored somewhere so
that it can be used when needed. Remember that variables are storage containers which have a datatype associated with it.
So to store a floating point value, we will need a floating point variable. Before, you take any input from the user, make sure
you have variables that can store that data.
First create Scanner class object (here sc ) and link it to the input stream as shown earlier.
Scanner sc = new Scanner(System.in);
Next, create a variable of the double datatype. Here we call our variable data.
double data;
Next, we assign the value that will be given by the user (through the Scanner class object sc using the nextDouble()
method in this case, with the variable that will hold it within our code.
data = sc.nextDouble();
This way, when the user enters a floating point value using the keyboard, our program will be able to capture it within the
double variable called data and thus we can access this value at any time after this point in code.
3 Scanner Class Example Code
A more concrete example in code will help us consolidate our recent learning about the Scanner class and how to use it get
user input. With that in mind, let us try to solve a simple problem - finding the sum of two integers that are given by the
user and then displaying that sum as the output. Before we start writing code, we need to understand what our objective is
and what kind of variables will we need to handle input and output data for this problem.
Objective: Compute and display the sum of two user input integers.
Steps:
• Declare and define a Scanner class object to handle user input
• Declare (and define if necessary) the co
ect number and type of variables needed
• Prompt the user for each input that we need
• Accept the user input using the Scanner class object and assign it to the co
ect variable defined earlie
• Compute the sum of the user inputs
• Display the sum
• Close the Scanner object
With the objective and how to go about it clearly defined, let us write code to solve this problem.
Listing 1: Scanner Class Example
1
Use the import keyword to import s p e c i f i c c l a s s e s OR en t i r e packages to your source code f i l e .
2
In t h i s case , we only r e qu i r e the Scanner c l a s s and t h e r e f o r e import a s i n g l e c l a s s i n to ou
3
source code f i l e .
4 import java . u t i l . Scanner ;
5
6
Def ine a c l a s s c a l l e d UserInputExample ( you can g ive the c l a s s any r e l e van t name o f your cho i c e ) .
7 class UserInputExample
8 {
9 public stat ic void main ( St r ing args [ ] )
We w i l l put a l l our source code with in the main ( ) method
10 {
11
To use the