The code copy is as follows:
import java.util.Scanner;
public class VariableExchange {
public static void main(String[] args){
System.out.println("Please enter the value of variable A");
Scanner scanner=new Scanner(System.in);
long A=scanner.nextLong();
System.out.println("Please enter the value of variable B");
Scanner scannerB=new Scanner(System.in);
long B=scannerB.nextLong();
System.out.println("A="+A+"/t"+"B="+B);
System.out.println("Execute variable swap...");
A=A^B;
B=B^A;
A=A^B;
System.out.println("A="+A+"/t"+"B="+B);
}
}
The implementation is to use XOR operation cleverly.
Its principle:
The code copy is as follows:
a = a ^ b;
b = b ^ a;
a = a ^ b;
Right now
The code copy is as follows:
a1=a^b
b=a1^b=(a^b)^b=a
a=a1^b =a1^(a1^b)=a1^a1^b=b
The same variable is equal to another variable and its XOR value.
This principle can also be applied to encryption. To XOR its value and key, you can get an encrypted string. The decryption operation only needs to XOR with key again.
Replenish:
Scanner class:
A simple text scanner that can use regular expressions to parse primitive types and strings.
Example 1:
The code copy is as follows:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Example 2:
The code copy is as follows:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}