Sam*_*m_C 2 java if-statement boolean try-catch
我是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);
Run Code Online (Sandbox Code Playgroud)
在if语句,循环或带括号{}的任何内容中声明的变量只能在这些括号内访问.要访问if语句之外的变量,请按以下方式声明:
boolean aa;
if(a == 1) {
aa = true;
System.out.println("a is " + aa + "(1)");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
117 次 |
| 最近记录: |