The Coder's Handbook

Console Input

THE SCANNER CLASS

Importing Scanner


You won't always need to input text from the console - it's a less common activity than making a variable or executing a loop. As a result, the Scanner class isn't a default part of Java. It is instead part of the standard library.


A library is a collection of code that anyone can use, but isn’t automatically loaded into every program. To use the scanner, you must first import it. You can import Scanner by typing the following line at the top of your program:


import java.util.Scanner;


Creating a Scanner


You can get input from the user with the Scanner object. To create a scanner, you’ll use the following line of code:


Scanner input = new Scanner(System.in);


In the above line, we’ve created a Scanner object with the name input.


Later in the course we’ll break down exactly what everything on this line means. For now, know that you can change the name input to anything.





Using Scanner


Once the Scanner is set up, you can use it to input both integers and strings using the following methods:

  • next() - Gets the next word the user types in as a String

  • nextInt() - Gets the next integer the user types in as an int

  • nextLine() - Gets the next line of text the user types in as a String

    • Tip: Avoid mixing nextLine() with next(). This can cause problems due to how line breaks work.


Code:

String name = “”;

int age = 0;


System.out.println(“What is your name?”)

name = input.next();


System.out.println(“How old are you?”);

age = input.nextInt();


Output:

What is your name?

> ...

How old are you?

> ...

RESOURCES