To read data from the user in java we
have three techniques –
1. System.in.read()
2. Scanner
3. BufferedReader
System.in.read() – It is an
abstract method which throws IOException. It reads next byte of data from the
input stream. The value byte is returned as an int in the range of 0 to 255. If
no byte is available because the end of the stream has been reached, the value
-1 is returned. This method blocks until input data is available, the end of
the stream is detected, or an exception is thrown.
It
takes input as an character and print its ASCII value. Its main disadvantage is
that it can take only one character at a time. And it only takes input as char and gives its ASCII code, to take other kind of input we
have to cast it.
Example –
import
java.io.IOException;
public class
Read {
public static void
main(String[] args) throws IOException {
System.out.println("Enter a character i will remain same but
print 1 char");
char a = (char)
System.in.read();
System.out.println(a);
}
}
Output –
Enter a character i will remain same
abc
a
Example –
import
java.io.IOException;
public class
Read {
public static void
main(String[] args) throws IOException {
//char b = System.in.read(); //cannot convert from
int to char
System.out.println("Enter any character i will print its ASCII
code");
int c = System.in.read();
System.out.println(c);
}
}
Output –
Enter any character i will print its ASCII code
A
65
No comments:
Post a Comment