[Java] Conditional Operator XOR
Start review Java recently, this post is written some practice about Conditional Operator - XOR.
If you want to see the Chinese version, please click here.
XOR
Full name about XOR is exclusive or or exclusive disjunction. It is a logical operation that outputs true only when inputs differ (one is true, the other is false). The following is the truth table about XOR.
XOR has reversibility which is different from other conditional operators. Give it an example,
Set X = 0010, Y = 1001, Z = X XOR Y
Z = X XOR Y = 0010 XOR 1001 = 1011
Z XOR X = 1011 XOR 0010 = 1001 = Y
Z XOR Y = 1011 XOR 1001 = 0010 = X
Using its characteristics, the following are its applications.
- Encryption
import java.util.Scanner;
public class XOR {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a password with a length of 6-12");
String password = sc.nextLine();
if(password.length() < 6) {
System.out.println("Please enter a password longer than 6");
} else if(password.length() > 12) {
System.out.println("Please enter a password with a length less than 12");
} else {
Key k = new Key();
System.out.println("Password:" + password);
System.out.println("Encryption:" + k.encryption(password));
System.out.println("Decrypt:" + k.decrypt());
}
}
}
class Key {
private String key = "rw14ff18DW8F";
private String encryptionPassword = "";
private String decryptPassword = "";
String encryption(String password) {
for (int i = 0; i < password.length(); i++) {
encryptionPassword += (char)(password.charAt(i) ^ key.charAt(i));
}
return encryptionPassword;
}
String decrypt() {
for (int i = 0; i < encryptionPassword.length(); i++) {
decryptPassword += (char)(encryptionPassword.charAt(i) ^ key.charAt(i));
}
return decryptPassword;
}
}
Input / Output
Please enter a password with a length of 6-12
jifjiVNE45
Password:jifjiVNE45
Encryption:W^0}pb
Decrypt:jifjiVNE45
- Value Swap
import java.util.Scanner;
public class ValueSwap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] swap = new int [2];
System.out.println("Please enter two integers.");
for (int i = 0; i < swap.length; i++) {
swap[i] = sc.nextInt();
}
ValueSwap.swap(swap);
}
public static void swap(int[] swap) {
swap[0] = swap[0] ^ swap[1];
swap[1] = swap[0] ^ swap[1];
swap[0] = swap[0] ^ swap[1];
}
}
Input / Output
Please enter two integer.
15 89
89 15
The above are some exercises on XOR. If you have any suggestions, please leave a message below. Thank you.