Java Reference
In-Depth Information
The
Item()
constructor in lines 12-25 takes four
String
objects as arguments and uses
them to set up the
id
,
name
,
retail
, and
quantity
instance variables. The last two must
be converted from strings to numeric values using the
Double.parseDouble()
and
Integer.parseInt()
class methods, respectively.
The value of the
price
instance variable depends on how much of that item is presently
in stock:
If more than 400 are in stock,
price
is 50% of
retail
(lines 18-19).
n
If between 201 and 400 are in stock,
price
is 60% of
retail
(lines 20-21).
n
For everything else,
price
is 70% of
retail
(lines 22-23).
n
Line 24 rounds off
price
so that it contains two or fewer decimal points, turning a price
such as
$6.92999999999999
to
$6.99
. The
Math.floor()
method rounds off decimal
numbers to the next lowest mathematical integer, returning them as double values.
After you have compiled
Item.class
, you're ready to create a class that represents a
storefront of these products. Create
Storefront.java
from Listing 6.3.
LISTING 6.3
The Full Text of
Storefront.java
1: package org.cadenhead.ecommerce;
2:
3: import java.util.*;
4:
5: public class Storefront {
6: private LinkedList catalog = new LinkedList();
7:
8: public void addItem(String id, String name, String price,
9: String quant) {
10:
11: Item it = new Item(id, name, price, quant);
12: catalog.add(it);
13: }
14:
15: public Item getItem(int i) {
16: return (Item)catalog.get(i);
17: }
18:
19: public int getSize() {
20: return catalog.size();
21: }
22:
23: public void sort() {
24: Collections.sort(catalog);
25: }
26: }