how to use NOT operator for integers in JAVA
when i put NOT operator (!) it shows an error package com.learnJava.first;
public class LogicalOpTable {
public static void main(String[] args) {
int p,q;
System.out.println("P\t Q\t AND\t OR\t XOR\t NOT\n");
p = 1;
q = 1;
System.out.println(p+ "\t " + q + "\t " + (p&q) + "\t " + (p|q) + "\t " + (p^q) + "\t " + !p );
p = 1;
q = 0;
System.out.println(p + "\t " + q + "\t " + (p&q) + "\t " + (p|q) + "\t " + (p^q) + "\t " + !p);
p = 0;
q = 1;
System.out.println(p + "\t " + q + "\t " + (p&q) + "\t " + (p|q) + "\t " + (p^q) + "\t " + !p);
p = 0;
q = 0;
System.out.println(p + "\t " + q + "\t " + (p&q) + "\t " + (p|q) + "\t " + (p^q) + "\t " + !p);
}
}
You would need to use the bitwise complement operator, ~
, not the logical complement operator, !
.
However, you seem to have a bit of a mismatch in your code: your class is called LogicalOpTable
, but you are otherwise using bitwise operators, not logical operators.
If you really want to do logical operations, using boolean
values instead of int
s.
If you really want to do bitwise operations, name your class so it's not as confusing ;)
one year later, but hey, maybe it's still relevant.
I had the same issue with this exercise, but I went a different way. If I'm not mistaken, p and q were initially of the boolean type and the task was to modify the table to show 1s and 0s instead of true and false.
What I did was convert each expression as a whole from boolean to int (e.g. int a = (!p) ? 1 : 0;) and replace them with the variable for the rest of the code (e.g System.out.println(..... + a); )
来源:https://stackoverflow.com/questions/44224702/how-to-use-not-operator-for-integers-in-java