One of the coolest moments when learning Java is making your program interact with you. Until now, your code has been shouting into the void with System.out.println()
statements, and the void (a.k.a. your console) has been silently nodding.
But what if you could make your program listen? Enter the Scanner
class, Java’s way of turning your static program into a two way conversation.
Step 1: Import the Scanner Class
Before you can use Scanner
, you have to invite it into your code. Think of this as adding someone to the group chat before you start sending them memes.
import java.util.Scanner;
Without this line, your program will stare at you blankly when you try to use Scanner
.
Step 2: Create a Scanner Object
To make your program listen, you create a Scanner
object. This is like giving your code a pair of ears.
Scanner input = new Scanner(System.in);
-
Scanner
= the type of object you are creating -
input
= the name you choose (you can call itkeyboard
,scanner
, or evenearholes
, but maybe keep it professional) -
System.in
= tells Java you want to take input from your keyboard
Step 3: Ask the User Something
Now your program is ready to listen, but it is polite to ask first. Use System.out.println()
to prompt the user.
System.out.println("What is your name?");
Step 4: Capture the Input
When the user types something and presses Enter, you can store it in a variable. For a full line of text, use nextLine()
.
String name = input.nextLine();
Now whatever the user typed is saved in the variable name. You can use it anywhere in your program.
Step 5: Respond Like a Chatty Friend
Finally, use that input to make your program respond.
System.out.println("Hello, " + name + "! Nice to meet you.");
Full Example
import java.util.Scanner;
public class Greeting {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is your name?");
String name = input.nextLine();
System.out.println("Hello, " + name + "! Nice to meet you.");
input.close();
}
}
Pro Tips
- Always close your
Scanner
with input.close() when you are done. It is like hanging up the phone politely. - For numbers, use
nextInt()
ornextDouble()
instead ofnextLine()
. - If things get weird (like
nextLine()
skipping inputs), it is probably becauseScanner
is still holding on to leftover input from before. It can be clingy, so you might need to add an extranextLine()
to clear the buffer.
Final Thoughts
Scanner is one of the first tools that makes your Java programs feel alive. It lets you collect information, personalise output, and generally be less of a monologue.
Next step? Combine it with conditionals and loops, and suddenly you have a program that not only listens but also makes decisions. Just do not let it get too smart, because that is how sci-fi movies start.
Top comments (0)