不用第三个变量从而达到交换变量x,y的值,无意在网上看到了这个问题,感觉很有意思,研究了一下,觉得用以下的办法来做最简单!:-)
假如 x = 2, y=3;
x = x + y;
y = x - y;
x = x - y;
这样就把x,y的值给换了,呵呵!
【code】:
class Exchange{
void doExchange(int x,int y){
x = x + y;
y = x - y;
x = x - y;
System.out.println("x="+x);
System.out.println("y="+y);
}
public static void main(String[] args){
Exchange ex = new Exchange();
ex.doExchange(2,3);
}
}
Result:
D:\jcode>javac Exchange.java
D:\jcode>java Exchange
x=3
y=2