2. SSBN Degree College, ATP M Vishnuvardhan
Introduction
Java primarily developed for Graphical User Interface, for this
reason Java doesn’t have explicit statement like scanf(). But however
we can read input into java program using the following ways.
1.Using System.in.read(): reads only one char in form of unicode
2.Using Stream classes (defined in java.io): very flexible and lot of
features provided. But they are bit complex and needs experience in
writing the programs
3.Using Scanner class (defined in java.util): very easy to use. Added
after jdk 1.5.0 only.
3. SSBN Degree College, ATP M Vishnuvardhan
How to read data using Scanner
The following steps are to be taken in order to read data
from Scanner class
1.Import util package (import java.util.*;)
2.Create an object to Scanner class
Scanner objName=new Scanner (Source);
1.Use appropriate method to read required data
4. SSBN Degree College, ATP M Vishnuvardhan
What is a source
Means from where the data is read in to the program. The source can
be keyboard, File on HDD, network computer, internet …
E.g: Scanner s=new Scanner (System.in);
Scanner s= new Scanner (new File(“D:Sample.txt”));
Source ProgramReading
Keyboard – System.in
File - FileReader or FileInputStream or File
Network – Socket
5. SSBN Degree College, ATP M Vishnuvardhan
Scanner methods
Scanner defines a rich set of methods
General Syntax
byte nextByte():
short nextShort():
int nextInt():
long nextLong():
Note: no explicit method to read single char in java
(i.e., there is no nextChar() )
float nextFloat():
double nextDouble():
boolean nextBoolean():
String next():
String nextLine():
xxx nextXxx():