|
Getting input from the user |
|
Getting input
from the user in Java requires us to get familiar with a built-in Java class called Scanner, which essentially allows us, programmers, to
process user input from the keyboard.
Similar to the System class, in which
we used the println operation (in programming terms, println is a method)
to display a statement to the screen, there are several methods in Scanner to input data of different types. Before we can refer to Scanner in our program, we have to have an import statement to tell the compiler where the Scanner class is located among the many other Java
built-in classes. Import statements go in the very beginning of the
program and in this case, it will be as follows: import java.util.Scanner; Now we need to
create a variable of type Scanner in order to start using it at getting input. Since the variable’s type is a class (not a
simple data type like int or double), this variable
refers to what Java calls an object. Compared to a variable of type int, an object is a
more complex entity and will require special handling. Here, beyond the variable declaration, an
additional statement is needed to create the object (i.e. setting aside the
memory for it). Let’s begin with the
variable declaration: Scanner input; Just as before,
the type of the variable goes first (in this case it’s the class Scanner), followed by the variable name, which is
input in this case. To create a Scanner object, we will need the following statement: input = new Scanner(System.in); Ok, so it looks
like a new Scanner object is being
created using the new operation and it’s going to be referred to by the
variable input (the variable input is the object reference). But what about System.in? Let’s
think back at output statements first.
The System.out prefix (it’s really an object), refers to the computer screen, so the
println operation
will send whatever is between the parentheses to the screen. In the case for input, System.in must
refer to the input device, which is just the keyboard. So essentially, the above Java statement
creates a Scanner object that will
intercept input from the keyboard using a variable called input.
Before we look at operations (or methods) to get input from, it’s helpful
to know that we can combine the last 2 statements into one as follows: Scanner input = new Scanner(System.in); This will
accomplish the declaration and object creation at the same time. Remember it’s possible to do the same with
variables of simple types. So instead
of having the two statements int plants; plants = 16; we can have the
single statement: int plants = 16; Ok, now we’re
ready to actually do something with our Scanner object. Let’s start with a simple
program of asking the user to enter an integer value, the number of books he
or she read this year. Whatever value
the user enters, it would make sense to create a variable for it since we can
expect to do something with its value later.
Also, if we’re prompting the user to enter some input, we will need an
output statement. So here’s what we
have so far: int books; System.out.println(“How many books have you read this year? “); At this point, we
would expect the user to enter some integer value on the keyboard. To intercept that value or read it into our
program, we will use our Scanner object input. As we already know, a Scanner has different methods to deal with different
types. In this case, since we’re
expecting an integer value, we will use the method nextInt (interpretation: get me the next value
entered on the keyboard as an integer).
Here’s the Java statement: books = input.nextInt(); The equal sign
(the assignment operator), will take the value that the user inputs, which is
intercepted by the method nextInt, and store it in the variable books. What’s to the right of the
assignment operator causes the method nextInt to execute – in programming terms, the method
is invoked. The syntax for
invoking a method is: objectReference.methodName.
If we’d like to see that this worked properly, we can now output the value of
the variable: System.out.println(“You have read “ + books + “ books.”); A couple minor
things about the program. The cursor
where the user types in a value is on the line following the prompt. This is because println inserts a ‘new line’ character. To change it, we can use print instead of println. Also,
instead of declaring the variable shoes then using it, we could have accomplished
everything in one statement: int books = input.nextInt(); Let’s put
everything together in a full program.
Everything that comes after the ‘//’ are comments, which are ignored
by the compiler. // The program
prompts the user to enter number of books and // then displays it
back to the screen // import to tell
the compiler where Scanner is import java.util.Scanner; public class InputTest { public static void main(String args[]) { // Create a Scanner object ‘input’ Scanner input = new Scanner(System.in); // prompt the user to enter number of
books System.out.print("How many books have you read this year? "); // store the result in ‘books’ int books = input.nextInt(); // display the value of ‘books’ System.out.println("You
have read " + books + " books"); } } Let’s try something a little more sophisticated. Instead of displaying the value that the
user entered, we will square it first then display the result. For this program, we’re going to need to
variable to store the user input, and another variable to store the
result. Here’s how the program goes: // this program will
square a number that the user enters import java.util.Scanner; public class SquareANumber { public static void main(String args[]) { //
Create a Scanner object ‘input’ Scanner input = new Scanner(System.in); // prompt the user to enter number of
shoes System.out.print("Enter
a whole number: "); // store the result in ‘number’ int number = input.nextInt(); // compute the square and store in
'square' int square =
number * number; // display the result System.out.println(number + " squared is " + square +
"."); } } |