Lesson 10
User Input
Author: Brandon Fajardo (9/24/17). Updated (8/6/20)
Introduction
Review: In the last lesson, you learned about loops, including while loops, do-while loops, and for loops. In general, the last lessons have involved pieces of code which are static. By this, we mean that any individual user running this code cannot affect the outcome externally.
Lesson topic: For this lesson, we will learn how we can interface with our code through the console. In this way, the user can input values which will then affect the result of the code.
Topic 1 - User Input
Subtopic 1 - Definition
User input: information inputted by the user to be processed by a program.
User input is often a useful feature of many pieces of software. It allows the user to interact with the code without having to know how to code themselves. By being able to interact with the code through user input, we are effectively providing a barrier between what the code does and what the user knows about how the code works. This idea of a barrier is actually a concept known as an abstraction barrier in computer science. In essence, an abstraction barrier is a useful way to structure code to allow programmers to divide their software into individual levels, such that beyond a certain level, it is not necessary to understand how a lower level actually works.
EX: Imagine using your computer and having to manually write each bit of information to your storage drive. That would be insane to have to do!
But an operating system (Windows, MacOS, Linux) is a kind of abstraction barrier. We can rely on our OS to perform all of these kinds of tasks for us, and we don’t even need to know how these processes work to use a computer effectively.
Subtopic 2 - Types of Input
To begin, there are a few ways our code can take in user input. One way to input values to our program is through program arguments. When we run a class in our IDE (IntelliJ), we are actually doing two steps.
First, we are compiling our code. This makes our code readable by our Java interpreter (the program which reads our code as instructions). Then, we are running what we have compiled. When we run what we have compiled, it is possible to pass in arguments to our class in the terminal. Another way to take user inputs is through the console. In Java, this can be achieved using the Scanner class (which will be the focus of this lesson).
Topic 2 - Creating a Scanner
As you may have noticed, we have been coding all of our code in classes. But what is a class?
A class is a collection of code to serve a particular purpose. If we would like to use the code from another class in our class, we can "instantiate" that other class in our class.
By instantiate, we mean to create a new instance of that class in our class. Once we have done this, we may use that class' code.
To save us programmers a little time, Java provides a whole structure of pre-made classes that we may use at our disposal. These classes have many features which are often useful to us. But to use them, we need to instantiate them. The Scanner class is one of these types of classes.
Scanner class: a class in Java used to take user input from the console.
Let us now describe the steps of how to instantiate the Scanner class. This process will resemble the processes used to instantiate other Java classes as well.
Note:
There exist certain special classes that do not need to be instantiated. One example of this is the Math class. We never instantiated a math class, but we were still able to use its functions. Ex: Math.round(), Math.pow(). But these are usually reserved for special utility classes.
Subtopic 1 - Importing Scanner
Because Scanner is a pre-made Java class, it exists within the Java source code but not our current project. To let our class know of its existence, we must import the Scanner class in our current class.
To import the Scanner class, use the following line of code:
*java.util is the folder which contains the Scanner class in the source code. We use . (dot) to specify these folders/directories.
This import statement is placed above everything else in the class, even before the class is defined.
In addition to Scanner, for most other pre-made Java classes (except certain exceptions previously mentioned), we will need to import their classes in the same way.
Subtopic 2 - Instantiating a Scanner
Now that we can access the Scanner class from our current class, we can instantiate a Scanner.
To instantiate a scanner, use the following notation:
We have successfully created a new Scanner. We can now utilize all of its functionalities and code.
Note:
You may notice that instantiating a Scanner is very similar to declaring and initializing a regular variable. The structure of the statements are actually the same: data_type NAME = value;
In this case, NAME is like an advanced variable which can hold an instance of a Scanner.
In addition, one can think of Scanner as an advanced data type.
Topic 3 - Using Scanner
Subtopic 1 - Taking in Inputs
The question now becomes, how can we use the properties of a Scanner?
Well, when we want to reference the properties of a class or instance of a class, we use dot notation.
Dot notation: the process of referencing a class’ properties by using dots to specify things.
The basic idea of dot notation is that we write the name of the class/instance we are referring to, a dot, and then the specific property we desire to use.
The basic notation for our Scanner instance would look like this:
Now, with a Scanner, we want to use the property which would allow us to take in user inputs from the console.
For this, we will utilize two of Scanner’s properties: next() and nextLine()
Note:
Notice that the way user input works is that input is by default taken in as a String. If necessary, we can convert these inputs into other data types.
Subtopic 2 - Using Inputs
Finally, we know the properties of Scanner which allow us to take in user inputs. Let’s see how we can actually use these inputs in our code.
The basic idea for using inputs is as follows:
To use inputs from the console, we will store them as variables.
Then, we use those variables however we desire in our code.
By assigning the value of NAME.next() (or NAME.nextLine()) to some variable, we will save the input to that variable:
Example: This program will print out the first word of what you inputted back to you.
Example: This program will take your name as an input and then greet you by your name.
Note:
When asking for an input from the user, it is helpful to specify what kind of input should be entered. This can be done by printing a prompt to the console using a print statement as shown above.
In certain situations, you may write a program that relies on the user to input exactly what you asked them for. But, the user may not do so (accidentally or purposefully). As a result, your code may not work, return weird results, or even error. We will teach you how to recover from these errors in the next lesson.
Example - Quadratic Formula
You may remember that we once coded the quadratic formula. Now, we can improve our code by allowing us to input the values for a, b, and c through user input.
Now anyone can use our program to calculate the quadratic formula! You could even use your program for your future homework assignments. And maybe even expand this calculator to solve other problems.
Note:
You may have noticed that we used the Scanner property, nextDouble(). As you can see, we are able to accept inputs for data types other than String as well. There are various other properties in Scanner which accept other data types which you can explore on your own. But be warned, if the user does not enter the appropriate data type, your code will error.
Example - Comparing Strings
Note:
When comparing Strings, we cannot use the regular == and != comparison operators like usual. Instead, we must use .equals().
Conclusion
Recap: As you can see, there is so much that can be done with user input. Try making programs on your own that utilize user input, and explore the possibilities.
Next: In the next lesson, you will learn about error handling, a valuable tool for when the user might not enter what your program expects, among other things.
Last updated