Scanner Class
A billing counter program isn't much use if every price is fixed in the code. Real programs ask: what's your name, how many tickets, which date. The most common way for a beginner Java program to read what the user types is the Scanner class. It reads from the keyboard and turns the text into the types you need: int, double, String.
Your First Scanner
import java.util.Scanner;
public class Greeting {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Your name: ");
String name = sc.next();
System.out.print("Tickets: ");
int tickets = sc.nextInt();
int fare = tickets * 120;
System.out.printf("%s booked %d tickets, Rs. %d%n",
name, tickets, fare);
}
}Your name: Tickets: Srihitha booked 3 tickets, Rs. 360When you run it yourself and type Srihitha and 3, the screen looks like this:
Your name: Srihitha
Tickets: 3
Srihitha booked 3 tickets, Rs. 360How it works
- Line 1 imports
Scannerfrom thejava.utilpackage. Without it, the compiler can't find the class. - Line 5 creates a
Scannerthat reads fromSystem.in, the keyboard. - Line 7:
next()reads one word. Line 9:nextInt()reads one whole number. print(notprintln) keeps the cursor next to each prompt, so the user types on the same line.
The output block above shows the prompts and the result on one line because what you type isn't part of the program's output.
Try it yourself: type Srihitha Anamaneni as the name. Why does the program crash or behave strangely?
The Reading Methods
| Method | Reads | Returns |
|---|---|---|
next() | One word (up to a space or new line) | String |
nextLine() | The rest of the current line, spaces included | String |
nextInt() | One whole number | int |
nextLong() | One whole number | long |
nextDouble() | One decimal number | double |
nextBoolean() | true or false | boolean |
hasNextInt() | Checks whether the next word is a whole number, without reading it | boolean |
How Scanner Sees Your Input
Scanner treats input as a stream of characters and splits it into tokens: pieces separated by spaces or new lines. The next...() methods take one token each. nextLine() is different: it takes everything up to the end of the current line.
The nextInt-Then-nextLine Trap
This is the most common Scanner bug. Read a number, then a full line:
import java.util.Scanner;
public class Trap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
String name = sc.nextLine();
System.out.println("[" + name + "] is " + age);
}
}[] is 25nextInt() reads 25 but leaves the Enter you pressed after it waiting in the input. Line 7's nextLine() reads up to that new line, finds nothing before it, and returns an empty string. The name you typed is never read.
The fix: after nextInt() (or nextDouble(), next()), call sc.nextLine(); once to throw away the rest of that line, then read the real line:
import java.util.Scanner;
public class Fixed {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
sc.nextLine();
String name = sc.nextLine();
System.out.println("[" + name + "] is " + age);
}
}[Srihitha Anamaneni] is 25When the User Types Something Wrong
If nextInt() finds abc instead of a number, it throws an InputMismatchException and the program stops. Check first with hasNextInt():
import java.util.Scanner;
public class SafeAge {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) {
System.out.println("Age: " + sc.nextInt());
} else {
System.out.println("Please type a whole number");
}
}
}Please type a whole numberCommon Mistakes
Forgetting the import. Without import java.util.Scanner; you get cannot find symbol: class Scanner.
Using next() for names with spaces. next() stops at the first space. Use nextLine() for full names and addresses.
Reading a line right after a number. Add the extra nextLine(), as shown above.
Interview Corner
Why does nextLine() return an empty string after nextInt()?
nextInt() reads only the digits and leaves the new-line character from the Enter key in the input. The following nextLine() reads up to that new line and returns the empty text before it. Call nextLine() once to discard it, or read every line with nextLine() and convert with Integer.parseInt.
What is the difference between next() and nextLine()?
next() returns the next token, stopping at a space or new line. nextLine() returns everything up to the end of the current line, including spaces, and moves past the new line.
Practice
- Easy: Ask for two whole numbers and print their sum and their product.
- Harder: Ask for a passenger's age (a number) and then their full name (with spaces). Print
Srihitha Anamaneni, 25. Make sure the name isn't empty.
Key Takeaways
Was this tutorial helpful?