-
Notifications
You must be signed in to change notification settings - Fork 47
/
Bag.java
89 lines (75 loc) · 1.79 KB
/
Bag.java
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.Iterator;
import java.util.Scanner;
public class Bag<Item> implements Iterable<Item>
{
private Node first; // µÚÒ»½áµã
private int N;
private class Node
{
Item item;
Node next;
}
public void add(Item item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
N++;
}
public boolean isEmpty()
{
return first == null; // Or: N == 0.
}
public int size()
{
return N;
}
public Iterator<Item> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Item> //ʵÏÖµü´úÆ÷
{
private Node current = first;
public boolean hasNext()
{
return current != null;
}
public void remove()
{
//null
}
public Item next()
{
Item item = current.item;
current = current.next;
return item;
}
}
public static void main(String[] args)
{
Bag<Double> numbers = new Bag<Double>();
String data = "10.0 20.0 30.0 40.0";
Scanner sc = new Scanner(data);
while (sc.hasNext())
{
numbers.add(sc.nextDouble());
}
sc.close();
int N = numbers.size();
double sum = 0.0;
for (double x : numbers)
{
sum += x;
}
double mean = sum / N;
sum = 0.0;
for (double x : numbers)
{
sum += (x - mean)*(x - mean);
}
double std = Math.sqrt(sum/(N-1));
System.out.printf("Mean: %.2f\n", mean);
System.out.printf("Std dev: %.2f\n", std);
}
}