To set up, we first import the Scanner class using the following line of code:
import java.util.Scanner;
Inputting a Line of Text
To start scanning inputs, we first create a new Scanner object.
public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); }}
Inside the constructor function Scanner() , we want to pass the field System.in so that it would start scanning inputs from the keyboard.
Next, to scan a line of text, we use the nextline() method from the Scanner class.
This function prompts the user for an input then returns the string we inputted.
We could utilize it by assigning its return value to a String variable.
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); }
After retrieving a string of text from the input, we can then close the scanner by using the method close() from the Scanner class.
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); scanner.close();}
Real-Life Examples
Problem
Create a program that prompts the user to enter their name.
Greet the user hello using the format:
Hello, <name>!
Solution
Main.java
public class Main {public static void main (String args) { String name; System.out.print("Please enter your name: "); Scanner scan = new Scanner(System.in); name = scanner.nextLine(); System.out.print("Hello, " + name + "!"); scanner.close(); }}