Java中如何将逻辑门输出赋值给变量?新手实现与门遇困
实现可绑定输出到变量的实用与门
你的现有代码存在几个核心问题:
- 局部变量与静态变量重名,导致静态变量未被有效复用
- 未将与运算结果存储到指定变量
- 核心逻辑未和输入变量建立关联
改进后的可复用实现
我们可以封装一个专注于与门逻辑的工具类,既完成布尔与运算,又能将结果绑定到变量:
public class AndGate { // 用于绑定与门输出的变量 private static boolean outputValue; // 核心方法:接收两个布尔输入,计算结果并绑定到变量,同时返回结果 public static boolean calculate(boolean input1, boolean input2) { outputValue = input1 && input2; return outputValue; } // 获取当前绑定的输出值 public static boolean getOutputValue() { return outputValue; } public static void main(String[] args) { // 测试场景1:两个true输入 boolean a = true; boolean b = true; boolean result = AndGate.calculate(a, b); System.out.println("运算结果:" + result); System.out.println("绑定变量的值:" + AndGate.getOutputValue()); // 测试场景2:一真一假输入 a = true; b = false; result = AndGate.calculate(a, b); System.out.println("运算结果:" + result); System.out.println("绑定变量的值:" + AndGate.getOutputValue()); } }
代码说明
calculate方法是核心:接收两个布尔输入,执行与运算后将结果赋值给outputValue变量,同时返回结果,实现“输出绑定到变量”的需求getOutputValue方法可以随时读取当前绑定的结果- 主方法中的测试用例展示了不同输入下的运算效果,且结果始终与绑定变量保持一致
多实例独立版本
如果需要同时使用多个互不干扰的与门(每个与门有自己的绑定变量),可以用非静态类实现:
public class IndependentAndGate { private boolean outputValue; public boolean calculate(boolean input1, boolean input2) { this.outputValue = input1 && input2; return this.outputValue; } public boolean getOutputValue() { return this.outputValue; } public static void main(String[] args) { IndependentAndGate gate1 = new IndependentAndGate(); gate1.calculate(true, true); System.out.println("门1的输出:" + gate1.getOutputValue()); IndependentAndGate gate2 = new IndependentAndGate(); gate2.calculate(true, false); System.out.println("门2的输出:" + gate2.getOutputValue()); } }
内容的提问来源于stack exchange,提问作者asiha Shirka
相关产品推荐
相关产品推荐

