Table of contents
1.
Introduction
2.
Scanner Class in Java
3.
Syntax
4.
Scanner Class Declaration
5.
How to get Java Scanner?
6.
Frequently Asked Questions
6.1.
What happens if I call nextchar() when there are no more characters available in the input source?
6.2.
Can I use nextchar() to read multiple characters at once?
6.3.
Is the character returned by nextchar() case-sensitive?
7.
Conclusion
Last Updated: Nov 12, 2024
Easy

Scanner and nextChar() in Java

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Java has many useful methods for working with strings. One such method is nextchar, which allows you to get the next character in a string easily. It belongs to the Scanner class, which provides methods for parsing text data from various sources like strings, files, or user input. The nextchar method allows you to retrieve the next character from the input source, making it easy to process text one character at a time. This method is very helpful when you need to analyze or manipulate strings character by character, like when validating user input, parsing formatted data, or implementing text-based algorithms. 

Scanner and nextChar() in Java

In this article, we'll discuss what nextchar does and how to use it properly. We'll cover the syntax for calling nextchar, and how to declare a Scanner to use it with code examples.

Scanner Class in Java

The Scanner class in Java provides a convenient way to read input from various sources, such as the keyboard, a file, or a string. It offers methods for parsing primitive types & strings using regular expressions. To use the nextchar method, you first need to create an instance of the Scanner class.


When you create a Scanner object, you specify the input source in the constructor. This could be System.in for reading from the standard input (keyboard), a File object for reading from a file, or a String for reading from a string. Once you have a Scanner instance, you can call its methods to read & parse the input as needed.


The Scanner class provides methods like next(), nextLine(), nextInt(), nextDouble(), & nextchar() to read different types of input. These methods allow you to read an entire word, a whole line, an integer, a floating-point number, or a single character, respectively. You can also use methods like hasNext(), hasNextLine(), hasNextInt(), hasNextDouble(), & hasNextchar() to check if the desired type of input is available before attempting to read it.

Syntax

The basic syntax for calling nextchar is :

char character = scanner.nextchar();


In this syntax:

- `scanner` is an instance of the Scanner class that you have created beforehand.
 

- `nextchar()` is the method call that retrieves the next character from the input source.
 

- The retrieved character is stored in the `character` variable, which is of type `char`.


It's important to note that the nextchar method reads a single character from the input source. If you want to read multiple characters or a complete line of text, you need to use a loop or other methods like next() or nextLine().


For example : 

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = scanner.nextchar();
System.out.println("You entered: " + ch);


In this example:

1. We create a Scanner object named `scanner` that reads input from the standard input (keyboard) using `System.in`.
 

2. We prompt the user to enter a character using `System.out.print()`.
 

3. We call `scanner.nextchar()` to read the next character entered by the user & store it in the `ch` variable.
 

4. Finally, we print the character that the user entered using `System.out.println()`.


The next char method provides a simple way to read individual characters from the input source, allowing you to process the input character by character as needed.

Scanner Class Declaration

Before you can use the nextchar method or any other methods of the Scanner class, you need to declare and initialize a Scanner object. The declaration of a Scanner object involves specifying the input source from which it will read data.

The syntax for declaring a Scanner object is:

Scanner scanner = new Scanner(input_source);


In this syntax:

- `Scanner` is the class name.

- `scanner` is the variable name you choose for the Scanner object.

- `input_source` is the source from which the Scanner will read input. It can be System.in for reading from the standard input (keyboard), a File object for reading from a file, or a String for reading from a string.


Here are a few examples of declaring Scanner objects with different input sources:

1. Reading from the keyboard:

Scanner scanner = new Scanner(System.in);


2. Reading from a file:

File file = new File("example.txt");
Scanner scanner = new Scanner(file);


3. Reading from a string:

String str = "Hello, World!";
Scanner scanner = new Scanner(str);


In the first example, we create a Scanner object that reads from the standard input using `System.in`. This allows us to read user input from the keyboard.

In the second example, we create a File object representing the file "example.txt." Then, we pass that File object to the Scanner constructor, enabling the Scanner to read input from the specified file.

In the third example, we create a Scanner object that reads from a string. We pass the string "Hello, World!" to the Scanner constructor, allowing the Scanner to read characters from that string.

How to get Java Scanner?

To use the Scanner class in your Java program, you must follow a few simple steps to set it up correctly.

Step 1: Import the Scanner class

At the top of your Java file, add the following import statement to import the Scanner class from the java.util package:

import java.util.Scanner;


This statement allows you to use the Scanner class in your code without having to fully qualify its name each time.


Step 2: Create a Scanner object

Once you have imported the Scanner class, you can create a Scanner object in your code. As mentioned earlier, you need to specify the input source when creating the Scanner object. 

This is an example of creating a Scanner object that reads from the standard input:

Scanner scanner = new Scanner(System.in);


In this example, we create a Scanner object named `scanner` & pass `System.in` as the input source, indicating that it will read input from the keyboard.


Step 3: Use Scanner methods

After creating the Scanner object, you can use its various methods to read & parse input. 

Let’s see an example that shows reading a character using the nextchar method:

System.out.print("Enter a character: ");
char ch = scanner.nextchar();
System.out.println("You entered: " + ch);


In this example, we prompt the user to enter a character using `System.out.print()`, then we call `scanner.nextchar()` to read the next character entered by the user. Finally, we print the entered character using `System.out.println()`.


Step 4: Close the Scanner (optional)

When you're done using the Scanner object, it's a good practice to close it to free up system resources. You can close the Scanner by calling the close() method:

scanner.close();


However, note that closing the Scanner object will also close the underlying input stream (e.g., System.in). So, be cautious when closing the Scanner if you plan to use the input stream again in your program.

Frequently Asked Questions

What happens if I call nextchar() when there are no more characters available in the input source?

 If you call nextchar() when there are no more characters available in the input source, the Scanner will throw a NoSuchElementException. To avoid this, you can use the hasNextchar() method to check if there is a character available before calling nextchar().

Can I use nextchar() to read multiple characters at once?

No, nextchar() is designed to read a single character at a time. If you want to read multiple characters, you can use a loop to call nextchar() repeatedly or use other methods like next() or nextLine() to read a sequence of characters.

Is the character returned by nextchar() case-sensitive?

Yes, the character returned by nextchar() is case-sensitive. It will return the exact character that is present in the input source, preserving its case.

Conclusion

In this article, we discussed the nextchar method of the Scanner class in Java. We learned how to declare a Scanner object, use the nextchar method to read characters, and saw examples of implementing them in a program. The nextchar method provides a convenient way to process input character by character, which makes it useful for tasks like parsing, validation, and text processing. 

You can also check out our other blogs on Code360.

Live masterclass