
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Read a Single Character Using Scanner Class in Java
From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. By default, whitespace is considered as the delimiter (to break the data into tokens).
Reading a character using the Scanner class
Scanner class provides nextXXX() (where xxx is int, float, boolean etc) methods which are used to read various primitive datatypes. But it never provides a method to read a single character.
But, you still can read a single character using this class.
- The next() method of the Scanner class returns the next token of the source in String format. This reads single characters (separated by delimiter) as a String.
String str = sc.next();
- The toCharArray() method of the String class converts the current String to a character array.
char ch[] = str.toCharArray()
- From the array you can get the character stored at the 0th position.
char myChar = ch[0];
Example
Following example reads a single character from the user using the Scanner class.
import java.util.Scanner; public class ContentsOfFile { public static void main(String args[]) throws Exception { //Creating a Scanner object Scanner sc = new Scanner(System.in); //Creating a StringBuffer object System.out.println("Enter your grade: (A, B, C, D)"); char grade = sc.next().toCharArray()[0]; if(grade == 'A'){ System.out.println("You are very good, you have been promoted"); }else if(grade=='B'){ System.out.println("You are good, you have been promoted"); }else if(grade=='C'){ System.out.println("You are average, you have been " + "promoted, you need to work hard"); }else if(grade=='D'){ System.out.println("You are not promoted, try again"); }else { System.out.println("Improper input"); } } }
Output
Enter your grade: (A, B, C, D) C You are average, you have been promoted, you need to work hard
Advertisements