how to use NOT operator for integers in JAVA

别等时光非礼了梦想. 提交于 2019-12-02 23:41:34

问题


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);


    }

}

回答1:


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 ints.

If you really want to do bitwise operations, name your class so it's not as confusing ;)




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!