Recall how boolean values are represented inside a computer program:
|
How we enter boolean inputs (values) from a keyboard
|
What is the problem:
|
The boolean input problem explained graphically (with a picture):
The keyboard cannot be used to enter the boolean representation for true !!!
|
Java's library contains a String ⇒ Boolean conversion method:
|
parseBoolean( ) converts its input string into the corresponding boolean representation:
The boolean output value of parseBoolean( ) is stored in a boolean typed variable
Description of the parseBoolean( ) method:
boolean parseBoolean( String s ):
return a boolean value depending
on input string s
If s is equal to "true", returns true (= 1)
If s is equal to "false", returns false (= 0)
|
The parseBoolean( ) is
very easy to
write
(That was
the main reason I
chose this
example to
introduce the
input conversion problem)
How is the method parseBoolean( ) implementated in Java:
public static boolean parseBoolean( String s ) { if ( s.comparesTo("true") == 0 ) return true; // Note: true ≡ binary number 00000001 else return false; // Note: false ≡ binary number 00000000 } |
Note 1: the statement return true will return the binary number 00000001 !!
Note 2: the statement return false will return the binary number 00000000 !!
DEMO: /home/cs255001/demo/java/String2Bool.java