Java Reference
In-Depth Information
The inString() method contains a while loop that terminates when the
user presses the input terminator key or when read() returns -1. If the
keystroke is not the <Return> key the input value is cast into a char type
and appended to a local string variable. This string is returned to the
callerwhenthemethodterminates.
An overloaded version of the inString() method flushes the input
stream, displays the user prompt, and then calls inString() to obtain in-
put.
Obtaining numeric data
Obtainingnumericdatafromthekeyboardconsistsofatwostepprocess:
first, we must retrieve the string of numeric characters typed by the user.
CommonlythisstringwillbeinASCIIformat.Second, convertthestringof
ASCIIdigitsintothedesiredJavaprimitive.Thefirststepisnotdifficult.We
canusetheinString()method,previouslydeveloped,inordertoobtainthe
digitstring.Parsingthestringofdigitsintoabinaryvalueisanothermatter.
One possible approach would be to take on the conversion task di-
rectly. In the case of a decimal integer string we could isolate each string
digit, proceeding left to right. Convert the ASCII value to binary by sub-
tracting 0x30. Then multiply each digit by the power of ten that corre-
spondstoitsplacevalue,andaccumulatethetotal.Theprocessingforan
integer conversion is relatively straightforward and could be accom-
plished in a fewlines of code. Much more complicated would be the con-
version of a decimal number in floating-point format. In this case we
would have to be familiar with the binary encoding defined in the
ANSI-IEEE 754 Standard, which is adopted by Java. These formats were
designed for computational efficiency; therefore they are not simple or
intuitive.
Fortunately,theparsingofthestringsintobinaryformatscanbeeasily
accomplishedusingmethodsprovidedinthejava.langlibrary.Inthispro-
cessingweusetheinString()method,developedintheprecedingsection,
toinputthestring.Theexpressionforobtainingthestringandconverting
intoanintegerformatisasfollows:
int aValue = Integer.valueOf
(inString().trim()).intValue();
In this case we use the trim() method to eliminate all spaces at either
end of the string obtained by the inString() method. The intValue()
method of the Integer class (located in java.lang) returns the integer
valueoftheexpression.Thentheparsingintoaninttypeisperformedby
Search WWH ::




Custom Search