"System.out"
meant for getting the output whereas System.in is standard input stream. This
stream is to accept the input data from valid specified input device such as
keyboard.
BufferedReader
BufferedReader
Read text using character-input stream and then buffering the characters to
provide for reading of characters. If size of buffer not specified then the
default size is used. While using readLine(), it is necessay to throw an I/O
Exception (input/out Exception). BufferedReader is part of java.io Library Package.
An
exception is an error that occurs within methods that creates an object that
represents the same exception and thrown in the method which caused the error.
Example
import
java.io.*;
public class Buffer_Reader
{
public static void main(String
args[])throws IOException
{
BufferedReader br=new
BufferedReader(new InputStreamReader(System.in));
int Inum;
double Dnum;
String S;
System.out.print("Enter
an Integer No. -> ");
Inum=Integer.parseInt(br.readLine());
System.out.print("Enter
a Real No. -> ");
Dnum=Double.parseDouble(br.readLine());
System.out.println("Integer No.
"+Inum);
System.out.println("Real No. "+Dnum);
}
}
Scanner
Class
Scanner
is a simple text scanner which allows
primitive data types and strings. Scanner also breaks the input into tokens using a delimiter, the
default is space.
Unlike
BufferedReader, Scanner never throw an unchecked exception. Although, the
Scanner class give option to accept data from specified input device like
keyboard and without handling exceptions. This may cause problem as it allows
non integer data while using nextInt(). in particular Scanner never throw an
IOException but a some of its constructors throw FileNotFoundException which is a subclass of
IOException. Java.util.Scanner, must be included to use Scanner Class.
Example
import
java.util.*;
public class ScanCl
{
public static void main(String
args[])//throws IOException
{
int N;
Scanner sc=new
Scanner(System.in);
System.out.print("Enter a No : ");
N=sc.nextInt();
System.out.println("Number = "+N);
}
}
DataInputStream
The
DataInputStream is also can use to read primitives and this too needs to throw
I/O Exception. It may give an warning because InputStream class is the abstract
class and an instance cannot be created of this class. DataInputStream is also
from java.io Library Package and it is necessary to throw an I/O Exception.
However, DataInputStream mainly used for reading from and writing to a data file.
Example
import
java.io.*;
class DataInp
{
public static void main(String
args[])throws IOException
{
int a;
DataInputStream DS = new
DataInputStream (System.in);
System.out.println("Enter a No. ");
a = DS.readInt();
}
}
No comments:
Post a Comment