Technology
Declaring and Using Scanner in Java: A Comprehensive Guide for Beginners
Declaring and Using Scanner in Java: A Comprehensive Guide for Beginners
When you're working on a Java project and need to obtain input, the Scanner class from the java.util package is an essential tool. This guide will walk you through how to declare a Scanner, read different types of input, and handle file scanning with best practices such as the try-with-resources block. By the end, you'll be able to effectively use the Scanner class in your Java programs.
Declaring a Scanner Object
The Scanner class is initialized by passing in the standard input stream, typically represented by the object.
Scanner sc new Scanner();
This Scanner object can then be used to read data from the keyboard, file input streams, or other sources.
Reading Input from the Keyboard
Here's a simple example to demonstrate how to create a Scanner object and read data from the keyboard:
import ;public class ScannerExample { public static void main(String[] args) { Scanner in new Scanner(); String name (); // Read a line of text int age (); // Read an integer // Closing the scanner is unnecessary when using try-with-resources (); // Not needed with try-with-resources }}
Reading Strings and Line-by-Line Input
Below is a more detailed example to read a string and line-by-line input from the keyboard:
import ;public class ScannerExample { public static void main(String[] args) { Scanner in new Scanner(); // Read a string String name (); ("Name is: " name); // Read a series of integers int num (); ("Number: " num); // Reading a line of text String line (); ("Line of text: " line); // Cleardown work with the scanner (); }}
Reading Input from a File
When reading input from a file, using the try-with-resources block is a good practice. This ensures that the file resources are automatically closed after the operations are completed.
Path filePath Path.of(sourceTxtFileLocation) ListString lines new ArrayListString(); String wordSeparatorRegex "[s, ] "; ```java try (Scanner scanner new Scanner(filePath)) { while (scanner.hasNextLine()) { ListString words (().split(wordSeparatorRegex)); (System.out::println); } } ```Extending the Scanner Class
While the default Scanner class is great for most use cases, you might want to extend it to suit more specific needs. Here's a basic example of extending the Scanner class:
import ;class CustomScanner extends Scanner { public CustomScanner(InputStream stream) { super(stream); } public int readInt() { return nextInt(); } public String readLine() { return nextLine(); }}public class CustomScannerExample { public static void main(String[] args) { String sourceFile "path/to/source-file.txt"; try (InputStream is new FileInputStream(sourceFile); Reader r new InputStreamReader(is, StandardCharsets.UTF_8); BufferedReader br new BufferedReader(r)) { CustomScanner scanner new CustomScanner(br); // Read data line-by-line String line; while ((line ()) ! null) { (line); } } catch (Exception e) { (); } }}
Core Methods of Scanner
Here are some commonly used methods of the Scanner class:
next() Returns the next token as a String. nextInt() Reads and returns the next token as an int value. nextDouble() Reads and returns the next token as a double value. nextLine() Returns the next line of text. nextChar() Returns the next character as a String. charAt() Returns the char at the specified index in the next token.For example:
Scanner scanner new Scanner();String line (); // Read a linechar firstChar ().charAt(0); // Read the first character of the next token
Best Practices with the try-with-resources Block
Using the try-with-resources block is highly recommended when dealing with file input streams as it ensures that the resources are properly closed after the block is executed:
try (InputStream is new FileInputStream(sourceFile); Reader r new InputStreamReader(is, StandardCharsets.UTF_8); BufferedReader br new BufferedReader(r)) { // Process the file} catch (IOException e) { // Handle exceptions}
Furthermore, if you need to handle streams or files, using InputStreamReader and BufferedReader in combination with Scanner is a good practice.
Conclusion
Reading input in Java is crucial for many applications, and Scanner is a powerful tool for achieving this. By understanding how to properly declare a Scanner, using it for various input types, and employing best practices like the try-with-resources block, you can handle input effectively in your Java projects.