运行结果展示:
实现代码如下:
import java.util.Scanner;
public class TwoNumberChange0414 {
public static void main(String[] args){
//交换数字的四种方法
int a,b,c;
a=1;
b=2;
System.out.println("交换前:"+"a="+a+","+"b="+b);
//方法1
// c=a;
// a=b;
// b=c;
// System.out.println("交换后:"+"a="+a+","+"b="+b);
//方法2
// a=a+b;//a=3
// b=a-b;//b=1
// a=a-b;
// System.out.println("交换后:"+"a="+a+","+"b="+b);
//方法3:
// a=a+b-(b=a);
// System.out.println("交换后:"+"a="+a+","+"b="+b);
//方法4:^异或运算
a=a^b;//a=0001^0010=0011=3
b=a^b;//b=0011^0010=0001=1
a=a^b;//a=0011^0001=0010=2
System.out.println("交换后:"+"a="+a+","+"b="+b);
}
}