-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInputGate.java
76 lines (67 loc) · 2.24 KB
/
InputGate.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
// InputGate.java
import java.util.Scanner;
/** Input gates will provide input to the simulation.
* @author Piotr Smietana
* @version 2019-04-29
* @see Gate
*/
public class InputGate extends Gate {
private float delay = Float.NaN;
private int initial = 0;
private int changeCount = 0;
/** Constructor, used only from within subclasses.
* @param sc the scanner
* @param name the name of the new gate
*/
public InputGate( Scanner sc, String name ){
super( name );
initial = ScanSupport.scanPositiveInt( sc, () -> this.toString() );
delay = ScanSupport.scanPositiveFloat( sc, () -> this.toString() );
changeCount = ScanSupport.scanPositiveInt( sc, () -> this.toString() );
if (initial > 1) Errors.warn( this + ": initial value > 1" );
ScanSupport.finishLine( sc, () -> this + ": followed by" );
}
/** Every subclass of gate offers a sanity check.
*/
public void sanityCheck() {
if (inCount != 0) {
Errors.warn( this.toString() + ": has unexpected input wires" );
}
// Launch the simulation!
if (initial == 1) {
this.outputChange( 1 );
}
if (changeCount > 0) {
Simulation.schedule(
delay, () -> this.nextChange( 1 - initial )
);
}
}
/** InputGate toString() method.
*/
public String toString() {
return super.toString() + " input "
+ initial + " " + delay + " " + changeCount;
}
// Simulation methods
/** Tell the gate that one of its inputs has changed.
* <p>
* Each subclass must implement this method.
* @param value the new value of that input
*/
public void inputChange( int value ) {
Errors.warn(this.toString() + ": impossible input change");
}
// Output change process for sequence of inputs
private void nextChange( int value ) {
changeCount = changeCount - 1;
// First change the output
this.outputChange( value );
// Second schedule the next change, if any
if (changeCount > 0) {
Simulation.schedule(
delay, () -> this.nextChange( 1 - value )
);
}
}
}