Java Reference
In-Depth Information
10
public
Stock(String theSymbol) {
11
if
(theSymbol == null) {
12
throw new
NullPointerException();
13 }
14
15 symbol = theSymbol;
16 totalShares = 0;
17 totalCost = 0.0;
18 }
19
20 // returns the total profit or loss earned on this stock,
21 // based on the given price per share
22 // pre: currentPrice >= 0.0
23
public double
getProfit(
double
currentPrice) {
24
if
(currentPrice < 0.0) {
25
throw new
IllegalArgumentException();
26 }
27
28
double
marketValue = totalShares
*
currentPrice;
29
return
marketValue - totalCost;
30 }
31
32 // records purchase of the given shares at the given price
33 // pre: shares >= 0 && pricePerShare >= 0.0
34
public void
purchase(
int
shares,
double
pricePerShare) {
35
if
(shares < 0 || pricePerShare < 0.0) {
36
throw new
IllegalArgumentException();
37 }
38
39 totalShares += shares;
40 totalCost += shares
*
pricePerShare;
41 }
42 }
Here's the client code to use the
Stock
class:
1 // This program tracks the user's purchases of two stocks,
2 // computing and reporting which stock was more profitable.
3
4
import
java.util.*;
5
6
public class
StockMain {
7
public static void
main(String[] args) {
8 Scanner console =
new
Scanner(System.in);
Search WWH ::
Custom Search