简体   繁体   English

用||构造Xor运算 和&&,无法获得正确的结果

[英]Construct a Xor Operation with || and &&, cannot run the right result

The following code would ask users to input a line of binary number( like 01010011 ), then the program need to Xor the first digit with the second one, if the result is true, return 1, if not, return 0. Then Xor this result with the third digit... until the last digit. 下面的代码将要求用户输入一个二进制数行(如01010011),然后程序需要将第一个数字与第二个数字进行异或运算,如果结果为true,则返回1,否则返回0。结果用第三个数字...直到最后一个数字。 Following is my code, I tried it for the whole night, but never got the correct result. 以下是我的代码,我整夜都在尝试,但从未获得正确的结果。 Can any one take a look at the code? 有人可以看一下代码吗? Thank you! 谢谢!

    char input1;
    char input2;

    Scanner scan = new Scanner( System.in );

    System.out.print("Please enter your value> ");
    input = scan.next();  


    input1 = input.charAt(0);

    for( int i = 1; i < input.length(); i++ )
    {
        input2 = input.charAt(i);

        if ( ( ( input1 == '1' || input2 == '0' ) && input1 != input2 )
                || ( ( input1 == '0' || input2 == '1' ) && input1 != input2 ) )
        {
            input1 = '1';
        }

        if ( input1 == input2 )
        {
            input1 = '0';
        }
    }

    System.out.println( "The result is " + input1 ); 

I would start with a xor method, return '1' iff a is one or b is one but both a and b are not one. 我将从xor方法开始, 如果 a为1 b为1,但ab都不为'1' ,则返回'1' Otherwise, return '0' . 否则,返回'0' That is an exclusive-or. 那是一个异或。 Like, 喜欢,

private static char xor(char a, char b) {
    boolean isa = (a == '1'), isb = (b == '1');
    if (isa || isb) {
        if (!(isa && isb)) {
            return '1';
        }
    }
    return '0';
}

Then your main needs to get the user input and iteratively xor the characters. 然后,您的main用户需要获取用户输入并反复对字符进行xor或。 Like, 喜欢,

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.print("Please enter your value> ");
    String input = scan.nextLine();
    char ch = input.charAt(0);
    for (int i = 1; i < input.length(); i++) {
        ch = xor(ch, input.charAt(i));
    }
    System.out.println("The result is " + ch);
}

Your code seems wrong in judgement, when input1 is 0, input2 is 1, your code will be wrong , it should be it: 您的代码在判断上似乎是错误的, 当input1为0,input2为1时,您的代码将是错误的 ,应该是:

    if ( ( ( input1 == '1' || input2 == '0' ) && input1 != input2 )
            || ( ( input1 == '0' || input2 == '1' ) && input1 != input2 ) )
    {
        input1 = '1';
    } 
    else if ( input1 == input2 )
    {
        input1 = '0';
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM