Java Scanner Class
In this page:
What is Scanner?
Scanner, from java.util, wraps an input source -- typically System.in for keyboard input, but it can just as easily read from a file -- and gives you convenient methods to pull out words, lines, or numbers.
Example: What is Scanner?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner("25 apples"); // wraps a source; System.in is typical, this is a hardcoded stand-in
System.out.println(sc.nextInt() + " " + sc.next());
}
}
Login to try C/C++/Java/PHP code in the editor
Reading Strings
next() reads input up to the next whitespace, so it stops at the first space in a name like 'John Smith'; nextLine() instead reads everything up to the newline, capturing the full line including spaces.
Example: Reading Strings
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner("John Smith");
System.out.println(sc.next()); // stops at the first space: "John"
Scanner sc2 = new Scanner("John Smith");
System.out.println(sc2.nextLine()); // reads the whole line: "John Smith"
}
}
Login to try C/C++/Java/PHP code in the editor
Reading Numbers
Methods like nextInt() and nextDouble() parse the next token as that specific numeric type and throw an InputMismatchException if what's typed doesn't actually look like a number.
Example: Reading Numbers
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner("42 3.14");
int whole = sc.nextInt();
double decimal = sc.nextDouble();
System.out.println(whole + " " + decimal);
}
}
Login to try C/C++/Java/PHP code in the editor
Checking for Inputs
Calling hasNextInt() before nextInt() lets you check whether the next token is actually a valid integer first, which is the standard way to validate user input without crashing on bad data.
Example: Checking for Inputs
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner("42");
if (sc.hasNextInt()) {
System.out.println("Valid int: " + sc.nextInt());
}
}
}
Login to try C/C++/Java/PHP code in the editor
Closing the Scanner
Scanner holds an open connection to its input source, so calling close() when you're done frees that underlying resource -- skipping this rarely causes visible problems for console input, but it's a resource leak for file-backed Scanners.
Example: Closing the Scanner
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner("done");
System.out.println(sc.next());
sc.close(); // frees the underlying resource
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: