gpt4 book ai didi

Java boolean 值未从 if 语句中传递出去

转载 作者:行者123 更新时间:2023-12-03 22:59:39 26 4
gpt4 key购买 nike

我是 Java 的新手,无法弄清楚为什么我的 if 语句中的 boolean 值不能传递到 System.out.println(aa + ""+ bb + ""+ gate); 下面。目标是在 if 语句中设置 boolean 值 aabb ,然后将这两个变量传递给另一个方法 calculate(aa , bb);.正确的值从每个 if 语句返回,但不是从 System.out.println(aa + ""+ bb + ""+ gate);。如何保存两个 boolean 值并将它们传递给其他东西?

 JButton btnCalculate = new JButton("Calculate");
btnCalculate.addActionListener(new ActionListener() {
JFrame error = new JFrame();
public void actionPerformed(ActionEvent arg0) {
try {
int a = Integer.parseInt(textInputA.getText());
int b = Integer.parseInt(textInputB.getText());
String gate = String.valueOf(comboBoxGateSelect.getSelectedItem());
if(a == 1) {
boolean aa = true;
System.out.println("a is " + aa + "(1)");
}
if(a == 0) {
boolean aa = false;
System.out.println("a is " + aa + "(0)");
}
if(b == 1) {
boolean bb = true;
System.out.println("b is " + bb + "(1)");
}
if(b == 0) {
boolean bb = false;
System.out.println("b is " + bb + "(0)");
}
if(a > 1 || a < 0) {
JOptionPane.showMessageDialog(error, "Input A must be either 1 or 0. \r\n True = 1, False = 0.", "Error", JOptionPane.ERROR_MESSAGE, null);
}
if(b > 1 || b < 0) {
JOptionPane.showMessageDialog(error, "Input B must be either 1 or 0. \r\n True = 1, False = 0.", "Error", JOptionPane.ERROR_MESSAGE, null);
}
System.out.println(a + " " + b + " " + gate);
System.out.println(aa + " " + bb + " " + gate); // This one +
calculate(aa, bb); // This one.
} catch(NumberFormatException e) {
JOptionPane.showMessageDialog(error, "Inputs A and B must be either 1 or 0. \r\n True = 1, False = 0.", "Error", JOptionPane.ERROR_MESSAGE, null);
}

}
});
btnCalculate.setBackground(Color.GRAY);
btnCalculate.setFont(new Font("Arial", Font.BOLD, 11));
btnCalculate.setForeground(Color.BLACK);
btnCalculate.setBounds(72, 204, 89, 23);
contentPane.add(btnCalculate);

最佳答案

在 if 语句、循环或任何带有括号 {} 的内容中声明的变量,可以在这些括号内访问。要在 if 语句之外访问变量,请像这样声明它:

boolean aa;    
if(a == 1) {
aa = true;
System.out.println("a is " + aa + "(1)");
}

关于Java boolean 值未从 if 语句中传递出去,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35024426/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com