The Scanner
class is a built-in class in Java that we use to process raw
input so we can use it in our programs. Typically, we'll use it for two
purposes:
System.in
)File
class)Following our typical object-oriented model, we'll want to create a Scanner
object, initialize it to scan something, and then we'll be able to grab chunks
of data, bit by bit.
The first thing you'll want to do is to create a scanner:
Scanner sc = new Scanner(System.in);
In this case, I'm declaring this scanner with the variable name sc
(it's my
personal preference). This means we are creating a new object whose type is
Scanner
. Thus, sc
just refers to one specific scanner we've made.
Then, I'm initializing a new scanner object by using the keyword new
, followed
by the type of object I'm initializing. In this case, I've decided I want this
object to be a Scanner
. Then, I'm passing in that I want to scan through
System.in
, which is user input from keyboards.
After that, I can scan for things! When we use scanners with System.in
, we
will ask the user for something every time we access a scanner method, such as
sc.nextLine()
. That'll ask for the next line of input from the user's
keyboard. If we just wanted the next word, we could do sc.next()
. If we want
the next integer, then sc.nextInt()
works great.
Prompting the user for input is as simple as asking for what you want, followed
by calling the methods of the scanner. These methods will return the value that
we captured from System.in
, so you'll want to assign their returned values to
variables.
System.out.println("Enter your name: ");
String name = sc.nextLine();
System.out.println("Enter your social security number: ");
int socialSecurity = sc.nextInt();
You can also scan information from files. This can be done by replacing System.in
with new File("filename")
.
Scanner sc = new Scanner(new File("the-great-gatsby.txt"));
Then, you can pull lines and words from the file just like you did with System.in
.
© 2019–2024 Jeffrey Wang. All rights reserved.
In loving memory of Haskell, 19??-2001.