Java Reference
In-Depth Information
System. out . println (
"1. Print cash balance, inventory, and prices"
);
System. out . println (
"2. Buy product"
);
System. out . println (
"3. Sell product"
);
System. out . println (
"4. I am done for today"
);
}
The new menu is much more intuitive and easy to use. Let us examine the different
menu items. For Choice 1, the program prints the cash reserves and information about all
the items. A
for
loop is used to iterate through the items. Note that we cannot use a for-
each
for
loop here because for every index we want to retrieve the item name, inventory,
and price. For Choices 2 and 3, the program calls the
getProductID
method. The method
asks the user to enter the name of the product and returns the index of the product. The
implementation is shown below.
public static int
getProductID()
{
String s ;
Scanner keyboard =
new
Scanner(System. in) ;
while
(
true
)
{
System. out . print (
"Enter product name: "
);
s = keyboard . next () ;
for
(
int
i=0;i
<
i t em . l e n g t h ;
i ++)
{
if
(item[i ].equals(s))
{
return
i;
}
}
}
}
The
getProductID
method asks the user to type in the name of the item. Textual input
is preferred when there are multiple items that are being traded. The method tries to match
the user input to one of the item names. If it is successful, it returns the index of the item.
Otherwise, it asks for user input again. Remember that we need to use the
equals
method
to compare strings.
Next, note that we have substituted the
buyApples
,
buyPears
,
sellApples
,and
sellPears
methods with just two methods:
buy
and
sell
. The introduction of arrays
has allowed us to simplify the design. The two methods are shown next.
public static boolean
sell(
int
itemID ,
int
amount)
{
if
(amount
>
inventory [ itemID])
{
return false
;
cash += amount
∗
price [itemID];
−
inventory [ itemID]
= amount ;
return true
;
}
public static boolean
buy(
int
itemID ,
int
amount)
{
if
(amount
price [itemID]
<
cash)
{
∗
cash
−
= amount
∗
price [itemID];
inventory [ itemID] += amount;
return true
;
return false
;
}
The novelty is that now the
itemID
is passed as a parameter. As a result, we do not have
to create separate methods for every item that is being traded. In summary, introducing