Parsing a string for boolean
In the examples in the 21 Days book, there are numerous instances where a String is parsed to produce some other value type like an int
or a float
using a statement such as i = int.parseInt(string)
. This makes perfect sense to me.
One of the exercises says this: Create a modified version of the Storefront
project that includes a noDiscount
variable for each item. When this variable is true
, sell the item at the retail price.
Seems simple enough. I took the GiftShop
class which defines the items for sale and added a "TRUE" or "FALSE" to each of them; that's not where the problem is. Through a couple of method calls the string values assigned to each item in GiftShop
get handed off to an Item
class. Item
takes all of the strings from GiftShop
and assigns them to String variables or parses them and assigns them to int
s or double
s. Both of those two operations use the following two statements:retail = Double.parseDouble(retailIn);
quantity = Integer.parseInt(quanIn);
Pretty straightforward at this point.
So I get to thinking, "Well I know that int
s and double
s are primitive but that there are objects which correspond to each of the primitives; that's what the whole Double.parseDouble
bit is about. I know there is also a Boolean object, so I'll do the same thing for my noDiscount
variable: I'll use something like this:private boolean = noDiscount;
/* unrelated code
when the String values come in from GiftShop, the "TRUE" or "FALSE" value comes in as "String discountIn"
so then I do this: */
noDiscount = Boolean.parseBoolean(discountIn);
But it doesn't work. When I compile the class, I get the following error back: Item.java:18: cannot resolve symbol
symbol : method parseBoolean (java.lang.String)
location: class java.lang.Boolean
noDiscount = Boolean.parseBoolean(discountIn);
^
1 error
But when I look at the API documentation, the method is there and is listed exactly the same as is the equivalent method for Integer:
static boolean | parseBoolean(String s) | Parses the string argument as a boolean.
and
static int | parseInt(String s) | Parses the string argument as a signed decimal integer.
What gives?