我对Java相当陌生,无法弄清楚为什么if语句中的布尔值不能传递到下面的System.out.println(aa + " " + bb + " " + gate);
中。目标是在if语句中设置布尔aa和bb的值,然后将两个变量都通过calculate(aa, bb);
传递到另一个方法中。正确的值是从每个if语句返回的,而不是从System.out.println(aa + " " + bb + " " + gate);
返回的。如何保存两个布尔值并将它们传递给其他值?
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 - Java boolean 值未从if语句中传递出去,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35024426/