Taking Character Input with Java Scanner

06 May 2023 Balmiki Mandal 0 Core Java

How to Take Character Input in Java Using Scanner

In this tutorial, we'll learn how to take a character input using the Scanner class in Java. We'll be using the next() method of the Scanner class to read a single character as an input. We'll also discuss the different ways to take a character input in Java.

Using the next() Method of Scanner Class

The easiest way to take a character input from the user is to use the next() method of the Scanner class. This method reads the next character from the input stream and returns it as a string.

Let's look at an example to understand it better:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // Read a single character
        String ch = sc.next();

        // Print the character
        System.out.println("You entered: " + ch);
    }
}

In this example, we have used the next() method to read a single character from the user. We've stored the character in a string variable and then printed it.

The output of this code will be something like this:

Enter a character: a
You entered: a

Using the nextLine() Method of Scanner Class

Another way to take a character input is to use the nextLine() method, which reads a line of text from the input stream. Since, a line of text may consist of more than one character, we can use the charAt() method of the String class to get the first character of the line.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // Read a line of text
        String line = sc.nextLine();

        // Get the first character
        char ch = line.charAt(0);

        // Print the character
        System.out.println("You entered: " + ch);
    }
}

In this example, we have used the nextLine() method to read a line of text from the user. We've then extracted the first character from the line and stored it in a character variable. Finally, we've printed the character.

The output of this code will be something like this:

Enter a character: hello
You entered: h

Conclusion

In this tutorial, we learned how to take a character input using the Scanner class in Java. We discussed two ways - using the next() method and the nextLine() method - and saw them through examples. Thanks for reading!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.