|
Example:
boolean x; x = true; |
|
|
We need to convert between these 2 different representations....
boolean parseBoolean( String s ): return a boolean value translated from
the input string s
If s == "true", we return true
If s == "false", we return false
String toString( boolean x ): return a String that represents the boolean
value x
If x == true, we return "true"
If x == false, we return false
|
See: click here
The method parseBoolean( ) performs the following translation:
Input Output
-------- -------------
"true" ---> true (= 1)
"false" ---> false (= 1)
|
The method toString( ) performs the following translation:
Input Output
----------- -------------
true (= 1) ---> "true"
false (= 0) ---> "false"
|
We write these methods to convert between the representations used by humans and the computer below
public class BooleanIO // I need to add IO to the name because the Boolean class
// is already defined inside the Java standard library
{
public static boolean parseBoolean( String s )
{
if ( s.equals("true") )
return true;
else
return false;
}
public static String toString( boolean x )
{
if ( x == true )
return "true";
else
return "false";
}
}
|
Scanner in = new Scanner( System.in );
String input;
boolean x;
System.out.print("Enter a boolean value: ");
input = in.nextLine();
x = BooleanIO.parseBoolean(input);
|
How to run the program:
|
boolean x;
x = Boolean.parseBoolean( "true" );
or
x = Boolean.parseBoolean( "false" );
|
See: click here