Chapter Table of Contents

Ch. 5 Scanner

Section Table of Contents

What is Scanner Conceptually?

So far we have used predeclared variables for values. But what if values were given or input to us by a user?

Scanner gets user input, which you see day to day in: login systems, games, chat rooms, and more!

How Scanner works: the Scanner class is imported, a Scanner object is made from it, and then the object is used to read in different input such as numbers or strings.

An example of how Scanner is used

Download the file FullName.java and run it. The output could look something like this, but will most likely look different depending on what you give the program as input.

<aside> 💡 The yellowish text is what the user types in.

</aside>

What is your first name? Inej
Whaht is your last name? Ghafa
Your full name is Inej Ghafa

Pretty cool, right? You can now interact with the computer! But what’s happening under the hood? Let’s take a look at the actual code that makes up this program.

import java.util.Scanner;

public class FullName {
	public static void main(String[] args) {
	// *create a Scanner object called input*
	Scanner input = new Scanner(System.in);

	// *prompt the user for their first name*
	System.out.print("What is your first name? ");

	// *read the input as a String*
	String firstName = input.nextLine();

	**// *prompt the user for their last name*
	System.out.print("What is your last name? ");

	// *read the input as a String*
	String firstName = input.nextLine();

	// *print the user's full name*
	System.out.println("Your full name is " + firstName + " " + lastName);

	}
}

💻 FullName.java

Importing Scanner

So let's break it down. First of all the import. You can import (bring) pieces of code from libraries so that you don't have to code it all from scratch. The java.util package (something containing a bunch of similar classes) has useful classes that you can utilize, such as Scanner.

<aside> 💡 To import a class, simply use the import keyword and then the location of the class:

</aside>