Using The Class To Get User Input: Java Util
Using The Class To Get User Input: Java Util
Using The Class To Get User Input: Java Util
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scannerclass documentation. In our example, we will use the nextLine() method,
which is used to read Strings:
import java.util.Scanner;
class MyClass {
System.out.println("Enter username");
Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read
other types, look at the table below:
Method Description
Built-in Packages
The Java API is a library of prewritten classes, that are free to use,
included in the Java Development Environment.
The library contains components for managing input, database
programming, and much more. The complete list can be found at Oracles
website: https://docs.oracle.com/javase/8/docs/api/.
The library is divided into packages and classes. Meaning you can either
import a single class (along with its methods and attributes), or a whole
package that contain all the classes that belong to the specified package.
To use a class or a package from the library, you need to use
the import keyword:
Syntax
import package.name.Class; // Import a single class
Import a Class
If you find a class you want to use, for example, the Scanner class, which is
used to get user input, write the following code:
Example
import java.util.Scanner;
To use the Scanner class, create an object of the class and use any of the
available methods found in the Scannerclass documentation. In our example, we
will use the nextLine() method, which is used to read a complete line:
Example
import java.util.Scanner;
class MyClass {
// String input
// Numerical input
BufferedReader in Java
BufferedReader is a Java class that reads text from the input stream. It buffers the characters so that it
can get the efficient reading of characters, arrays, etc. It inherits the reader class and makes the code
efficient since we can read the data line-by-line with the readline() method. There are a few pointers we
have to keep in mind while working with BufferedReader class in Java.
We may have to specify the buffer size even though the default is large enough for any purpose.
With each request made of a reader a corresponding, a read request is also made of an
underlying character.
It is always advised to wrap a BufferedReader class around any reader such as
InputStreamReaders.
For the programs that use DataInputaStreams for textual input, an appropriate BufferedReader
replaces the DataInputStream to localize it.