February 26th, 2013, 10:29 PM
XOR operation simulation
I have to do the following in Java:
I'm just not even sure where to begin. Could someone point me in the right direction?
I think I can figure out how to perform an XOR on two characters, but I'm not sure how to get those characters out of the string in the manner I need. I know how to get a character from a certain position in the string, but I need to do more than that I think.
This assignment comes from a chapter on loops, so I assume the solution contains at least one loop. Material covered in class so far includes data types, variables, constants, arithmetic operators, classes, if, if/else, if/else/if, switch, and loops.
February 26th, 2013, 10:58 PM
I think I actually may have just gotten it because the actual outputs match my expected outputs, unless I just have no clue how to evaluate the binary numbers with XOR by hand.
Does this look right?
//Import the Scanner class
public class XOR
public static void main (String args)
//Instantiate a Scanner object
Scanner scan = new Scanner(System.in);
//Ask user for a binary number
System.out.print("Enter a binary number (0s and 1s) > ");
String binaryNumber = scan.next();
//Declare a variable for the index of the last character
int lastIndex = binaryNumber.length() - 1;
//Declare variables for characters
char character1 = binaryNumber.charAt(0);
//Run a for loop for each character of the string
for (int i = 0; i < lastIndex; i++)
//Set character2 to the character to the right of position i
character2 = binaryNumber.charAt(i + 1);
//XOR character1 and character2
if ((character1 == '0' || character2 == '0') && !(character1 == '0' && character2 == '0'))
character1 = '1';
character1 = '0';
//If the XOR operation on the string results in 1, print true; otherwise, print false.
if (character1 == '1')
February 27th, 2013, 12:40 AM
Hint: the operator for the exclusive-OR is the ^
February 27th, 2013, 12:45 AM
I've missed class several times, but as far as I know, we haven't learned that, so I don't think we're expected to use that operator. Plus, we're supposed to simulate that operation, so I don't think we're supposed to actually use it.
Originally Posted by Aurum84
Wouldn't this code basically be doing what the ^ operation would do?
((character1 == '0' || character2 == '0') && !(character1 == '0' && character2 == '0'))
February 27th, 2013, 05:39 AM
Change the '0' to a '1' and you will be correct.