我是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);
答案 0 :(得分:6)
在if语句,循环或带括号{}的任何内容中声明的变量在这些括号内只能 。要访问if语句之外的变量,请按以下方式声明:
boolean aa;
if(a == 1) {
aa = true;
System.out.println("a is " + aa + "(1)");
}
答案 1 :(得分:0)
if语句,while循环等内部调用的所有变量只能通过括号内的命令访问。您必须在括号之前声明变量,如下所示:
boolean myBool;
if (true) {
myBool = true;
} else {
myBool = false;
}
希望这有帮助!