Wednesday, July 3, 2024
HomeLanguagesJavaScanner and nextChar() in Java

Scanner and nextChar() in Java

Scanner class in Java supports nextInt(), nextLong(), nextDouble() etc. But there is no nextChar() (See this for examples) To read a char, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string, the number 0 in the function in CharAt(NUMBER)  represents the index of the single word of the string taken input, and set that index character to the char variable.

Java




// Java program to read character using Scanner
// class
import java.util.Scanner;
 
public class ScannerDemo1 {
 
    public static void main(String [] args){
 
        Scanner sc = new Scanner(System.in);
        char c = sc.next().charAt(1);
                                // here this is the indexing of the element to take //
        System.out.println("c = "+c);
 
 
 
 
    }
     
}
   
   
  


Input :

ge

Output :

c = e

This article is contributed by Piyush Gupta and Soumen Pal. If you like Lazyroar and would like to contribute, you can also write an article and mail your article to review-team@neveropen.co.za. See your article appearing on the Lazyroar main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Previous article
Next article
Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments