In Java, the Scanner
class is part of the java.util
package and is used for reading input from various sources, such as the keyboard or a file.
Method | Description |
---|---|
Scanner(InputStream source) |
Constructs a new Scanner that produces values scanned from the specified input stream. Common sources include System.in for standard input or any other InputStream . |
Scanner(File source) |
Constructs a new Scanner that produces values scanned from the specified file. |
Scanner(String source) |
Constructs a new Scanner that produces values scanned from the specified string. |
next() |
Finds and returns the next complete token from the scanner. |
nextLine() |
Advances the scanner to the next line and returns the content of that line. |
nextInt() |
Scans the next token as an int . |
nextDouble() |
Scans the next token as a double . |
nextBoolean() |
Scans the next token as a boolean . |
hasNext() |
Returns true if there is another token in the input, otherwise false . |
hasNextInt() |
Returns true if the next token can be interpreted as an int , otherwise false . |
hasNextDouble() |
Returns true if the next token can be interpreted as a double , otherwise false . |
useDelimiter(String pattern) |
Sets the delimiter pattern to the specified regular expression. By default, the delimiter is set to whitespace. |
close() |
Closes the Scanner . It is good practice to close the scanner when it is no longer needed. |
Here's a simple example of using the Scanner
class to read user input from the console:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Hello, " + name + "! You are " + age + " years old.");
// Don't forget to close the scanner
scanner.close();
}
}