Java Scanner Class

http‮//:s‬www.theitroad.com

In Java, the Scanner class is a utility class that allows you to read input from the keyboard or from a file. It provides methods for reading different types of input, such as integers, floats, doubles, strings, and characters.

To use the Scanner class, you first need to create an instance of the class and pass the input source as a parameter to the constructor. For example, to read input from the keyboard, you can create a Scanner object that reads from the standard input stream (System.in), like this:

Scanner scanner = new Scanner(System.in);

Once you have a Scanner object, you can use its various methods to read input. For example, to read an integer value, you can use the nextInt() method, like this:

int x = scanner.nextInt();

Similarly, to read a double value, you can use the nextDouble() method, like this:

double y = scanner.nextDouble();

To read a string, you can use the next() method, which reads a single word, or the nextLine() method, which reads a whole line of text. For example:

String name = scanner.next();
String line = scanner.nextLine();

The Scanner class also provides methods for checking if there is more input to read, and for skipping over input that you don't want to read. For example, to check if there is another integer to read, you can use the hasNextInt() method, like this:

if (scanner.hasNextInt()) {
    int z = scanner.nextInt();
}

To skip over the next character, you can use the next() method with a regular expression that matches the character you want to skip, like this:

scanner.next("[,.;]");

Finally, when you are finished using the Scanner object, you should close it to release any system resources that it may be holding. You can do this by calling the close() method, like this:

scanner.close();

Here is an example of using the Scanner class to read input from the keyboard and perform some simple calculations:

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number: ");
int x = scanner.nextInt();

System.out.print("Enter the second number: ");
int y = scanner.nextInt();

int sum = x + y;
int difference = x - y;

System.out.println("The sum is: " + sum);
System.out.println("The difference is: " + difference);

scanner.close();

In this example, we use the nextInt() method to read two integer values from the keyboard, and then perform some simple calculations with them. The System.out.println() statements output the results of the calculations. Finally, we close the Scanner object to release system resources.