Java Reference
In-Depth Information
Flushing the input stream
TheOutputStreamclasscontainsamethodtoflushthestreambutthereis
noflush()methodinInputStream.Thismeansthat,occasionallycodemay
calltheread()methodandencounterunexpectedcharactersthathavenot
yet been removed from the stream. This is likely to happen when we at-
tempttoremoveasinglecharacterfromthestream,asisthecasewhenat-
tempting to retrieve a single character. One of the methods of the Keyin
class, called inputFlush(), addresses this potential problem by ensuring
thattherearenodatabytespendingintheinputstream.
The inputFlush() method uses the available() method of the InputStream
class. This method returns the number of bytes that can be read without be-
ing blocked. The method returns zero if there is no data pending to be re-
moved in the input stream. This can be interpreted to mean that the stream
is clear and that the next call to the read() function will be blocked. The
codefortheInputFlush()methodisasfollows:
public static void inputFlush()
{
int dummy;
int bAvail;
try
{
while((System.in.available()) != 0)
dummy = System.in.read();
}
catch(java.io.IOException e)
{
System.out.println("Input error");
}
}
The inputFlush() method contains a while loop that repeats while the
input stream is not clear. In each iteration, the byte in the input stream is
read into a variable named dummy and discarded. When the method re-
turns,codecanassumethattheinputstreamcontainsnospuriousdata.
Obtaining character data
TwomethodsoftheKeyinclassreadcharacterdata.Onereadsandreturns
a string and the other one a char variable. The method named inChar() is
usedtoinputasinglecharacter.
public static char inChar(String prompt)
{
int aChar = 0;
Search WWH ::




Custom Search