创建一个类,在该类中定义两个变量并为其指定初始值,然后交换两个变量的值,要求不允许借助第三个变量,只能使用异或运行实现两个变量值的交换。
import java.util.Scanner; public class VariableExchange { public static void main(String[] args){ System.out.println("请输入变量A的值"); Scanner scanner=new Scanner(System.in); long A=scanner.nextLong(); System.out.println("请输入变量B的值"); Scanner scannerB=new Scanner(System.in); long B=scannerB.nextLong(); System.out.println("A="+A+" "+"B="+B); System.out.println("执行变量互换..."); A=A^B; B=B^A; A=A^B; System.out.println("A="+A+" "+"B="+B); } }
效果如图所示: