Get Character

In this example given below, we will learn how to read character from keyboard
and display on standard output device. Method System.in.read() read character
from keyboard and returns integer value of the character so we need to change
type to char.
Here is the code of GetCharMethod
import java.io.*;
public class GetCharMethod
{
public static void main(String args[]) throws IOException
{
char c;
System.out.println("Enter any character or Enter
the charater E to exit");
while ( ( c = getChar() ) != 'E' )
{
System.out.println("You have entered " + c);
}
}
static public char getChar() throws IOException
{
char ch = (char) System.in.read();
input();
return ch;
}
static public void input() throws IOException
{
while ( (char) System.in.read() != '\n' );
}
}
|
Output will be displayed as:

Download Source Code