我给你四种方法:后面两种是不需要第三方变量,就能完成交换的.
class SwapFunction{
/*方法一:
public static void main(String[] args)
{
int x=6,y=45;
System.out.println("x="+x+","+"y="+y);//未换位之前
int temp=x;//temp=6
x=y;//x=45
y=temp;//y6
System.out.println("x="+x+","+"y="+y);//换位之后
}
*/
/*方法二:
public static void main(String[] args)
{
int x=4,y=9;
System.out.println("x="+x+","+"y="+y);//未换位之前
x=x+y;//x=13
y=x-y;//y=4
x=x-y;//x=9
System.out.println("x="+x+","+"y="+y);//换位之后
}
*/
//方法三:
public static void main(String[] args){
int x=3;
int y=7;
System.out.println("x="+x+","+"y="+y);//未换位之前
x=x^y;//x^y
y=x^y;//x^y^y
x=y^x;//x^y^x
System.out.println("x="+x+","+"y="+y);//换位之后
}
/*方法四:
public static void main (String[])
{
int x=4,y=8;
System.out.println("x="+x+","+"y="+y);//未换位之前
x=(x+y-(y=x);//y=x=4,x=8
System.out.println("x="+x+","+"y="+y);//换位之后
}
*/
}
|