可以通过异或^不会改变变量本身的值这一特性,方便快捷的实现两个整数互换
代码如下:
public class Example5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个整数:");
int a = scanner.nextInt();
System.out.println("请输入一个整数:");
int b = scanner.nextInt();
System.out.println("交换前的值:");
System.out.println("a = " + a + "\tb = " + b);
a = a^b;
b = b^a;
a = a^b;
System.out.println("交换后的值:");
System.out.println("a = " + a + "\tb = " + b);
scanner.close();
}
}
运行结果如下: