Java Scanner Class

Java scanner class is a class in Java that allows developers to read data from different input sources. The Java scanner class is used to read input data from different sources like the keyboard, a file, or even a network stream. It scans the input data and breaks it into tokens, which can then be processed or used in the program.

The scanner class is easy to use, and it can be used to read data of different types, including strings, integers, and floating-point numbers.

This article will provide a comprehensive guide to the Java scanner class, its importance in Java programming, and how to use it effectively. The article will cover topics such as installation, basic syntax, reading input from the console, using delimiters, handling exceptions, and commonly used functions. A table of all the functions and corresponding syntax will be provided in the article.

By the end of the article, readers will have a solid understanding of the Java scanner class and how to use it in their Java programs.

Getting Started with Java Scanner Class

Installation of Java Development Kit

Before getting started with Java Scanner Class, make sure that you have Java Development Kit (JDK) installed on your computer. You can download and install the latest version of JDK from the official Oracle website.

Creating a new project in Eclipse IDE

Next, you need to create a new Java project in Eclipse IDE. To do this, launch Eclipse and select File > New > Java Project. Give the project a name and click Finish.

Importing the Java scanner class

To use the Java Scanner class, you need to import it into your project. You can do this by adding the following line of code at the beginning of your Java file:

import java.util.Scanner;

The basic syntax of Java scanner class

The basic syntax of Java Scanner Class is as follows:

Scanner scanner = new Scanner(System.in);

Here, “scanner” is the name of the Scanner object, and “System.in” represents the input stream from the keyboard. You can replace “System.in” with any other input stream, such as a file or a network socket.

In summary, getting started with Java Scanner Class involves installing the Java Development Kit, creating a new project in Eclipse IDE, importing the Java Scanner class, and understanding the basic syntax of the Scanner class. Once you have completed these steps, you can start using the Scanner class to read user input in your Java programs.

Reading Input from Console using Java Scanner Class

Java scanner class provides various methods to read input from the console. These methods can read different types of data, such as strings, integers, floats, and doubles.

Reading string input using scanner class

To read a string input from the console using the scanner class, we can use the next() method. This method reads the next string from the console until it encounters a whitespace character.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.next();
System.out.println("Hello, " + name);

Reading integer input using scanner class

To read an integer input from the console using the scanner class, we can use the nextInt() method. This method reads the next integer from the console.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
System.out.println("You entered " + num);

Reading float input using scanner class

To read a float input from the console using the scanner class, we can use the nextFloat() method. This method reads the next float from the console.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a float number: ");
float f = scanner.nextFloat();
System.out.println("You entered " + f);

Reading double input using scanner class

To read a double input from the console using the scanner class, we can use the nextDouble() method. This method reads the next double from the console.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a double number: ");
double d = scanner.nextDouble();
System.out.println("You entered " + d);

Using Delimiters in Java Scanner Class

Explanation of delimiter in scanner class

The delimiter in Java scanner class is used to split input data into separate tokens. By default, the delimiter used is whitespace.

Setting custom delimiter in scanner class

To set a custom delimiter, use the useDelimiter() method. For example, to use a comma as a delimiter:

Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(",");

Using multiple delimiters in scanner class

You can use multiple delimiters by specifying them as a regular expression pattern. For example, to use both commas and semicolons as delimiters:

Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("[,;]");

In this case, the scanner will split the input data into separate tokens whenever it encounters either a comma or a semicolon.

Handling Exceptions in Java Scanner Class

Explanation of InputMismatchException

  • InputMismatchException is a runtime exception that occurs when the input provided by the user doesn’t match the type of data that program is expecting.
  • This exception is thrown when the input provided by the user cannot be parsed into the type of data that the program is expecting.

Explanation of NoSuchElementException

  • NoSuchElementException is a runtime exception that occurs when there is no more input to be read by the Scanner object.
  • This exception is thrown when the Scanner object tries to read input that doesn’t exist.

Handling exceptions using try-catch block

  • To handle exceptions in Java, we use the try-catch block.
  • In the try block, we put the code that may throw an exception.
  • In the catch block, we catch the exception and provide the code to handle the exception.

Example code to handle InputMismatchException:

Scanner scanner = new Scanner(System.in);
try {
    int num = scanner.nextInt();
} catch (InputMismatchException e) {
    System.out.println("Invalid input. Please enter an integer value.");
}

Example code to handle NoSuchElementException:

Scanner scanner = new Scanner(System.in);
try {
    String input = scanner.nextLine();
} catch (NoSuchElementException e) {
    System.out.println("No more input to read.");
}

Commonly Used Functions in Java Scanner Class

The Java Scanner class provides many functions that make it easier to read and process user input. Here are some of the commonly used functions:

hasNext() function:

This function returns true if the scanner has another token in its input.

next() function:

This function returns the next complete token from the scanner’s input.

nextLine() function:

This function reads the next line of input as a string.

hasNextLine() function:

This function returns true if there is another line of input available to read.

nextInt() function:

This function reads the next token as an integer.

hasNextInt() function:

This function returns true if the next token in the scanner’s input can be interpreted as an integer.

nextDouble() function:

This function reads the next token as a double.

hasNextDouble() function:

This function returns true if the next token in the scanner’s input can be interpreted as a double.

useDelimiter() function:

This function sets the scanner’s delimiter to a specified pattern.

Here is an example of how to use some of these functions:

import java.util.Scanner;
public class Main {
   public static void main(String[] args) {
      
      Scanner scanner = new Scanner(System.in);
      
      System.out.println("Enter your name:");
      String name = scanner.nextLine();
      System.out.println("Your name is: " + name);
      
      System.out.println("Enter your age:");
      int age = scanner.nextInt();
      System.out.println("Your age is: " + age);
      
      scanner.nextLine(); // consume the \n character
      
      System.out.println("Enter your favorite color:");
      String color = scanner.nextLine();
      System.out.println("Your favorite color is: " + color);
      
      scanner.close();
   }
}

Output:
Enter your name:
FirstCode
Your name is: FirstCode
Enter your age:
22
Your age is: 22
Enter your favourite color:
Blue
Your favourite color is: Blue

In this example, we create a Scanner object to read input from the console. We use the nextLine() function to read a string, nextInt() function to read an integer, and nextLine() function again to read a string after the integer. We also use the close() function to close the scanner after we are done reading input.

Conclusion

In this article, we discussed the Java Scanner Class and its importance in Java programming. We covered how to import the Java Scanner Class and the basic syntax of the class.

We also explained how Java Scanner Class is a powerful tool for reading input from the console in Java. It provides various functions for reading different types of input, including strings, integers, and doubles. Additionally, it allows for the use of custom delimiters and exception handling.

With this knowledge, you can enhance your Java programming skills and develop more efficient and effective programs.

Leave a Reply

Your email address will not be published. Required fields are marked *