Java Scanner Class
In Java, capturing user input is a critical part of interactive applications. One of the most popular ways to handle input is by using the Scanner class, which is part of the java.util
package. The Scanner class makes it easy to parse and read data from various input sources, such as keyboard input, files, and streams.
The Scanner class in Java is used to read input from different sources such as keyboard input, files, and other data streams. It simplifies the task of parsing and tokenizing input, allowing developers to read various data types such as integers, floats, strings, and more.
int
, float
, String
, etc.).System.in
(keyboard), files, and strings.To use the Scanner class, you need to import it from the java.util
package:
import java.util.Scanner;
The Scanner class provides several methods to read different types of input. Here are some of the most commonly used methods:
Method | Description |
---|---|
next() |
Reads the next token as a string. |
nextInt() |
Reads the next token as an integer. |
nextDouble() |
Reads the next token as a double. |
nextLine() |
Reads the entire line as a string. |
hasNext() |
Returns true if there is another token. |
hasNextInt() |
Returns true if the next token is an integer. |
hasNextDouble() |
Returns true if the next token is a double. |
You can use the next()
or nextLine()
method to read strings from the user. The difference is that next()
reads a single word, while nextLine()
reads the entire line.
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Reading a single word
System.out.print("Enter a word: ");
String word = scanner.next();
System.out.println("You entered: " + word);
// Reading a full line
System.out.print("Enter a sentence: ");
scanner.nextLine(); // Consume the newline character
String sentence = scanner.nextLine();
System.out.println("You entered: " + sentence);
scanner.close();
}
}
Explanation:
next()
reads the first token (word) until a space is encountered.nextLine()
reads the entire line of text, including spaces.You can use methods like nextInt()
and nextDouble()
to read numbers from the user.
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Reading an integer
System.out.print("Enter an integer: ");
int num = scanner.nextInt();
System.out.println("You entered: " + num);
// Reading a double
System.out.print("Enter a decimal number: ");
double decimal = scanner.nextDouble();
System.out.println("You entered: " + decimal);
scanner.close();
}
}
Explanation:
nextInt()
reads an integer value from the user.nextDouble()
reads a decimal (double) value from the user.Sometimes, you may want to read both strings and numbers in a mixed format. You can use the nextLine()
method after reading a number to handle this case.
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Reading an integer
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// Consume the remaining newline character after nextInt()
scanner.nextLine();
// Reading a string (name)
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello " + name + ", you are " + age + " years old.");
scanner.close();
}
}
Explanation:
nextInt()
, a nextLine()
call is needed to consume the newline character left by nextInt()
. This ensures that the next nextLine()
correctly reads the entire string.Sometimes, you may need to validate whether the user entered a valid input type, such as checking if the next token is an integer or a double. The hasNextInt()
and hasNextDouble()
methods come in handy here.
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Checking if the next input is an integer
System.out.print("Enter a number: ");
if (scanner.hasNextInt()) {
int num = scanner.nextInt();
System.out.println("You entered: " + num);
} else {
System.out.println("That's not a valid number!");
}
scanner.close();
}
}
Explanation:
hasNextInt()
checks if the next token can be interpreted as an integer. If it is, you can safely use nextInt()
to read it.The Scanner class can also be used to read data from files. To do so, you need to pass a File
object or FileInputStream
to the Scanner constructor.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileInputExample {
public static void main(String[] args) {
try {
// Create a Scanner to read from a file
File file = new File("input.txt");
Scanner fileScanner = new Scanner(file);
// Reading each line from the file
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
System.out.println(line);
}
fileScanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
}
Explanation:
Scanner
object is created using a File
object, allowing you to read from the file line by line using nextLine()
.Close the Scanner: Always close the Scanner
object when you’re done with it using scanner.close()
. This is particularly important when reading from files or streams to free up resources.
Use nextLine()
to Read Full Lines: When reading input that may contain spaces, use nextLine()
to capture the full line of text.
Input Validation: Use hasNext()
methods (e.g., hasNextInt()
, hasNextDouble()
) to check if the input matches the expected type before trying to read it.
Handle Input Mismatch Exceptions: Be prepared to handle InputMismatchException
if the input type doesn’t match the expected one. You can catch this exception to provide meaningful feedback to the user.