forked from rick2785/JavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetTheStock.java
More file actions
68 lines (42 loc) · 1.59 KB
/
GetTheStock.java
File metadata and controls
68 lines (42 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.text.DecimalFormat;
public class GetTheStock implements Runnable{
// Could be used to set how many seconds to wait
// in Thread.sleep() below
// private int startTime;
private String stock;
private double price;
// Will hold reference to the StockGrabber object
private Subject stockGrabber;
public GetTheStock(Subject stockGrabber, int newStartTime, String newStock, double newPrice){
// Store the reference to the stockGrabber object so
// I can make calls to its methods
this.stockGrabber = stockGrabber;
// startTime = newStartTime; Not used to have variable sleep time
stock = newStock;
price = newPrice;
}
public void run(){
for(int i = 1; i <= 20; i++){
try{
// Sleep for 2 seconds
Thread.sleep(2000);
// Use Thread.sleep(startTime * 1000); to
// make sleep time variable
}
catch(InterruptedException e)
{}
// Generates a random number between -.03 and .03
double randNum = (Math.random() * (.06)) - .03;
// Formats decimals to 2 places
DecimalFormat df = new DecimalFormat("#.##");
// Change the price and then convert it back into a double
price = Double.valueOf(df.format((price + randNum)));
if(stock == "IBM") ((StockGrabber) stockGrabber).setIBMPrice(price);
if(stock == "AAPL") ((StockGrabber) stockGrabber).setAAPLPrice(price);
if(stock == "GOOG") ((StockGrabber) stockGrabber).setGOOGPrice(price);
System.out.println(stock + ": " + df.format((price + randNum)) +
" " + df.format(randNum));
System.out.println();
}
}
}