Java Reference
In-Depth Information
possible is a good idea. An extra advantage is that the increased reusability of the method
does not increase its complexity.
public static int
getQuantity(String product , String action)
{
System. out . print (
"How many "
+ product +
" do you want to "
+action
+
"? "
);
Scanner keyboard =
new
Scanner(System. in) ;
return
keyboard . nextInt () ;
}
Lastly, consider the four transaction methods.
public static boolean
sellApples(
int
amount)
{
if
(amount
>
appleInventory)
{
return false
;
cash += amount
applePrice ;
∗
appleInventory
−
= amount ;
return true
;
}
public static boolean
sellPears(
int
amount)
{
if
(amount
>
pearInventory)
{
return false
;
cash += amount
∗
pearPrice ;
pearInventory
−
= amount ;
return true
;
}
public static boolean
buyApples(
int
amount)
{
if
(amount
applePrice
<
cash)
{
∗
cash
−
= amount
∗
applePrice ;
appleInventory += amount;
return true
;
return false
;
}
public static boolean
buyPears(
int
amount)
{
if
(amount
pearPrice
<
cash)
{
∗
pearPrice ;
pearInventory += amount;
return true
;
return false
;
cash
−
= amount
∗
}
The methods are very similar. However, combining them in a single method is not easy, as
explained earlier. The buy methods check to see if the player has enough money to complete
the transaction. If this is the case, then the purchase is complete and the cash and inventory
are adjusted accordingly. Similarly, the sell methods check to see if the player has enough
inventory. If this is the case, then the cash and the inventory are updated appropriately.
Note that defining the variables
cash
,
pearInventory
,
appleInventory
,
pearPrice
,and
applePrice
as global variables significantly simplifies the four methods.
Compile and run the complete program. See how much money you can make in 10 days.