How to Read Character in JavaJava Scanner class provides nextInt() method for reading an integer value, nextDouble() method for reading a double value, nextLong() method for reading a long value, etc. But there is no nextChar() method in the Scanner class to read a character in Java. In this section, we will learn how to take character input in Java. To read a character in Java, we use next() of the Scanner class method followed by chatAt() at method of the String class. Java next() MethodThe next() method is a method of Java Scanner class. It finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. It may block while waiting for input to scan, even if a previous invocation of hasNext() return true. Syntax: The method throws the NoSuchElementException if no more tokens are available. It also throws IllegalStateException if the scanner is closed. Java chatAt() MethodThe charAt() is a method of the Java String class. It returns the char value at the specified index (range from 0 to length()-1). In a character sequence, the first character index value is 0, the next at index 1, and so on. Syntax: The method throws IndexOutOfBoundsException if the index argument is negative or not less than the length of the string. To read a character in Java, we use next() method followed by charAt(0). The next() method returns the next token/ word in the input as a string and chatAt() method returns the first character in that string. We use the next() and charAt() method in the following way to read a character. The following program takes a character from user, as input and prints the same character. CharacterInputExample1.java Output: Input a character: R You have entered R CharacterInputExample2.java Output: Input a character: W You have entered W Next TopicJava Tutorial |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India