Java Reference
In-Depth Information
if
(! sellPears(amount))
{
System. out . println (
"You don't have enough pears"
);
break
;
}
}
}
while
(choice != 7);
System. out . println (
"You finished with:"
+ currencyFormatter(cash)) ;
}
...
}
Note that the constants are defined at the beginning of the
TradingGame
class. It is
pretty common for constants to be defined at the beginning of a class so that they can be
easily changed. The price of apples and pears will be computed as a random number in the
range (
BASE PRICE
-
VARIATION
,
BASE PRICE
+
VARIATION
).
The variable
cash
keeps track of the amount of cash available to spend. Note that most
of the variables are defined as global and are accessible by several methods. Consider for ex-
ample the variable
cash
.The
buyPears
,
buyApples
,
sellApples
,and
sellPears
methods
all need to update this variable. Remember that a method can just perform a calculation
and cannot modify an input variable of primitive type, such as a
double
. Therefore, the
easiest choice here is to make the variables global. It makes sense to define a variable that
is updated by several methods as global. Note that the methods could not simply return
the new value of the modified variable because most methods update two variables (e.g.,
appleInventory
and
cash
) and a method cannot return two values.
Next, let us examine the
main
method in details. Our program needs to do something
every day. Therefore, we create a
for
loop that iterates through the days. At the beginning
of every day, we will set the apple price and the pear price using the
computePrice
method.
The method will compute a random price using the input parameters. Next, we will print
the current day and the menu. Here is the menu.
1. Print cash balance and inventory
2. Print today
's prices
3. Buy apples
4. Sell apples
5. Buy pears
6. Sell pears
7. I am done for today
Note that we have combined some choices in some menu items. For example, Choice 1
prints both the balance and the inventory. From psychology, we know that humans have
hard time keeping track of more than 7 items. Therefore, creating a menu that has 10 or
more items usually signals a bad user interface.
We next need a loop that allows the player to enter her or his menu choice multiple
times. After the player enters her or his choice, we need to perform the operation that the
player requested. Since this sequence will always be executed at least once, we are using a
do
-
while
loop. The loop will keep iterating until the user selects Choice 7.
Note that we have broken the choice selection into two methods. The
printMenu
method
prints the available choices, while the
getChoice
method gets input from the player. We
have created two methods because creating a single method that performs multiple tasks
signals a poor design. Such a method contains more complex logic, which makes it more
error-prone. Moreover, methods that perform multiple tasks are rarely reusable.