基本情報技術者試験 平成14年度・秋期・午後 問8 ソースプログラム
class Wire {
private boolean value;
public boolean getValue() { return value; }
public void setValue(boolean value) { this.value = value; }
}
abstract class Gate {
protected Wire[] input;
protected Wire output;
public Gate(int nInputs) {
input = new Wire[nInputs];
for (int i = 0; i < nInputs; i++) { input[i] = new Wire(); }
output = new Wire();
}
public void connectOutputTo(Gate otherGate, int nthInput) {
try {
input[nthInput] = otherGate.output;
} catch (Exception e) {
e.printStackTrace();
}
}
public Wire getInput(int n) { return input[n]; }
public Wire getOutput() { return output; }
abstract public void tick();
}
class NotGate extends Gate {
public NotGate() { super(1); }
public void tick() { output.setValue(!input[0].getValue()); }
}
class AndGate extends Gate {
public AndGate() { super(2); }
public void tick() { output.setValue(input[0].getValue() && input[1].getValue()); }
}
public class LogicCircuitTest {
public static void main(String[] args) {
Gate not = new NotGate();
Gate and = new AndGate();
not.connectOutputTo(and, 0);
not.getInput(0).setValue(false);
and.getInput(1).setValue(true);
not.tick();
and.tick();
System.out.println(and.getOutput().getValue());
}
}