Hi ............
There are many way to get input in java. Java works on two type of stream 1. Character Stream 2. Byte Stream
Java treats Char data type different form c and c++. In C/C++ char data type hold 7 bit ASCII Character which is 0 to 127 characters but java char data type works on Unicode.
{
public static void main(String args[]) throws Exception
{
char ar[]=new char[5];
int i;
for(i=0;i<ar.length;i++)
{
ar[i]=getChar();
}
}
static char getChar() throws Exception
{
char ch=(char) System.in.read();
pressEnter();
return ch;
}
static void pressEnter() throws Exception
{
while((char) System.in.read()!='\n');
}
}
There are many way to get input in java. Java works on two type of stream 1. Character Stream 2. Byte Stream
Java treats Char data type different form c and c++. In C/C++ char data type hold 7 bit ASCII Character which is 0 to 127 characters but java char data type works on Unicode.
- System.in.read() takes one character from user and return correspondence int value
- for hold it we have to type cast in char
- System.in.read() stop when user press enter its take it '\n'
{
public static void main(String args[]) throws Exception
{
char ar[]=new char[5];
int i;
for(i=0;i<ar.length;i++)
{
ar[i]=getChar();
}
}
static char getChar() throws Exception
{
char ch=(char) System.in.read();
pressEnter();
return ch;
}
static void pressEnter() throws Exception
{
while((char) System.in.read()!='\n');
}
}
- As we know System.in.read() stop input when it encounter newline
- i have make getChar function which is taking input from user and sure newline using pressEnter function
- pressEnter is use to ensure newline character using while loop
- loop stop when user press enter otherwise it looking in stream for new line