Scanner class in Java

In Java, the Scanner class is a part of the java.util package and provides a convenient way to read input from various sources, such as the keyboard, files, or streams. It simplifies the process of parsing and tokenizing input data into different data types like integers, floats, strings, etc.

Follwoing is an example of how to use the Scanner class to read input from the keyboard:

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."); scanner.close(); } }

In this example, we create a Scanner object called scanner and pass System.in as an argument to its constructor. System.in represents the standard input stream, which is typically the keyboard. We then use the nextLine() method to read a line of text from the user, and the nextInt() method to read an integer from the user.

After reading the input, we use the retrieved data to display a personalized message to the user. Finally, we close the Scanner using the close() method to release system resources properly.

The Scanner class provides various methods to read input of different data types like nextInt(), nextDouble(), nextBoolean(), etc. It also has methods like next() and nextLine() to read strings and lines of text, respectively. Additionally, the Scanner class has methods like hasNextInt(), hasNextDouble(), etc., which can be used to check if the next input is of a particular data type before reading it.

Read data from files using Scanner class

Apart from reading input from the keyboard, the Scanner class can also be used to read data from files or streams. Here's an example of reading input from a file:

import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class FileScannerExample { public static void main(String[] args) { try { File file = new File("data.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }

In this example, we create a Scanner object called scanner and pass a File object representing the file "data.txt" to its constructor. We then use a while loop to read each line from the file using the nextLine() method until there are no more lines to read.

Conclusion

The Scanner class in Java is a powerful tool for reading input in a simple and flexible way. It is widely used in various applications for tasks like interactive user input, file parsing, and data extraction. However, it's essential to handle exceptions properly when working with files or other input sources that may not be available or accessible.