Java is very versatile in its ability, but can become even more versatile with the integration of user input. One way to have user input is the Scanner Class. This class allows the programmer to scan the keyboard and get input from the user.
How to Instantiate the Scanner Class
Since it is not built into the regular Java library, it needs to be imported. It can be imported like so:
or
Note: All imports are declared at the top of the program before the main method like so:
The first way of importing shown above just imports the Scanner Class, whereas the second imports the entire utility library.
Once it is imported, you can create an instance of the class. This is done like so:
Scanner name = new Scanner(System.in);
This name can be anything. For example:
Methods in the Scanner Class
next() – This grabs the next input which can be any number of characters until it encounters a break.
This looks like:
nextLine() – This grabs the next whole line until it encounters a new line character, “\n”.
This looks like:
nextInt() – This grabs the next int
This looks like:
Note: All other number types follow the same layout as int does. For example nextDouble(), nextFloat(), etc.
If reading from a text file, it is useful to know if there is more input. This can be done by calling hasNext(). hasNext() just like next() can be specified to a certain variable type like so: hasNextInt(), hasNextLine(), etc.
Asking the User for Input
To ask the user for input, a message must be output. There are two ways in which this can be done.
or
The first outputs the message in the brackets, then has a built in new line character. The second will output, then stay on the same line until otherwise told. So to output something where the user inputs on the same line as the output, the latter is preferred.
This looks like this:
Which outputs this to the console: