You are on page 1of 14

JAVA USER INPUT

Jennifer H. Caño
San Mateo Senior High School
J.H.Caño
Java User Input
1.Built-in Packages
2.Importing packages
3.java.util.scanner;
4.User Input

J.H.Caño
Java Packages & API
A package in Java is used to group related
classes. Think of it as a folder in a file
directory. We use packages to avoid name
conflicts, and to write a better
maintainable code. Packages are divided
into two categories:
• Built-in Packages (packages from the Java API)
• User-defined Packages (create your own
packages)

J.H.Caño
BUILT-IN PACKAGES
• Java API has many pre-written classes to
help the programmer manage input,
database and etc. These are free to use
included in the Java Development
Environment.
• 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.

J.H.Caño
BUILT-IN PACKAGES
• To use a class or a package from the
library, you need to use the import
keyword:

J.H.Caño
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

J.H.Caño
Java User Input
• The Scanner class is used to get user
input, and it is found in the java.util
package.
• To use the Scanner class, create an
object of the class and use any of the
available methods found in the Scanner
class documentation.
• It is the easiest way to read input in a
Java program, though not very efficient if
you want an input method for scenarios
where time is a constraint like in
competitive programming.

J.H.Caño
Java User Input
• To create an object of Scanner class, we usually
pass the predefined object System.in, which
represents the standard input stream. We may
pass an object of class File if we want to read
input from a file.
• To read numerical values of a certain data type
XYZ, the function to use is nextXYZ(). For
example, to read a value of type short, we can
use nextShort()
• To read strings, we use nextLine().
• To read a single character, we use
next().charAt(0). next() function returns the next
token/word in the input as a string and charAt(0)
function returns the first character in that string.

J.H.Caño
java.util.Scanner
• A class in the java.util Package
that helps programmers handle
inputs from the user.

J.H.Caño
INPUT TYPES

J.H.Caño
SAMPLE CODE 1

J.H.Caño
SAMPLE CODE 2

J.H.Caño
SAMPLE CODE 3

J.H.Caño
SAMPLE CODE 4

J.H.Caño

You might also like