Logical expressions in java
So on Java , an "AND" statement is &&, "OR" statement is ||...
What about for XOR then... that is if I have two choices. I HAVE to pic开发者_如何学运维k one, but I can't pick both.
HOWEVER,
private class CheckBoxListener implements ItemListener{
public void itemStateChanged(ItemEvent e)
{
if(one.isSelected()^two.isSelected()){
thehandler handler = new thehandler();
button.addActionListener(handler);
}
}}
Even if I have both checkboxes selected, the button is 'enabled'. This is the handler for the button fyi:
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent event){
dispose();
}
So if both are selected, and If i click the button. the frame should not dispose. It should only dispose when either one of them is selected.
^
is the XOR operator in Java.
Regarding your Swing problem, the problem is that you are not inspecting the state of the checkboxes when the button is clicked, but rather when the checkboxes are selected. You should instead have something like this:
private class ButtonActionListener implements ActionListener {
/*
* You will probably define a constructor that accepts the two checkboxes
* as arguments.
*/
@Override
public void actionPerformed(ActionEvent event) {
if (one.isSelected() ^ two.isSelected()) {
dispose();
}
}
}
The alternative approach is to create one instance of the ActionListener
. You would add it with addActionListener
when exactly one of the checkboxes is checked, and remove it with removeActionListener
otherwise:
private class CheckBoxListener implements ItemListener {
private ActionListener buttonActionListener = new thehandler();
@Override
public void itemStateChanged(ItemEvent event) {
if(one.isSelected() ^ two.isSelected()) {
button.addActionListener(buttonActionListener);
} else {
button.removeActionListener(buttonActionListener);
}
}
}
You can use the !=
operator. For two booleans it has the same truth table as an "actual" XOR operator.
As pointed out in other answers, the xor operator for boolean (and bitwise) expressions is ^
.
boolean a = true;
boolean b = false;
boolean c = a ^ b; // c == true
(It should also be noted that &
and |
works just fine for boolean expressions too.)
So, why does &&
and ||
exist, but not ^^
?
The explanation is evident if you consider the difference between &
and &&
.
The first one (&
) does not short-circuit the evaluation, while &&
does. So logically, ^^
would correspond to the short circuited version of ^
. But, there is no way ^
can be short-circuited (no matter what the first operand evaluates to, the second operand needs to be evaluated) so ^^
would be completely redundant.
^
is the boolean logical exclusive OR
All of Java's operators, including XOR.
http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Way to go
boolean xor = a ^ b;
You can do it the long way. This is a logical XOR.
!(p && q) && (p || q)
You use the ^ character.
See Creating a "logical exclusive or" operator in Java
精彩评论