java中如何编写一个调换两个数的子函数?我用
public void exchange(int x,int y)
{
int temp;
if(x>y)
{
temp=x;
x=y;
y=temp;
}
}
不行,再调用时,改变不了实际参数的值!
public void exchange(int x,int y)
{
int temp;
if(x>y)
{
temp=x;
x=y;
y=temp;
}
}
不行,再调用时,改变不了实际参数的值!
public int[] exchange(int[] x)
{
int temp;
if(x[0] > x[1])
{
temp=x[0];
x[0] = x[1];
x[1] = temp;
}
return x;
}
public class debug
{
public debug()
{
}
public static void main(String[] args) {
debug d=new debug();
Wrapper a=d.new Wrapper(1),b=d.new Wrapper(2);
change(a,b);
System.out.println("after charge,a="+a+",b="+b);
}
class Wrapper {
private int value=0;
public int getValue() {return value;}
public void setValue(int i) {value=i;}
public Wrapper(int i) {value=i;}
public String toString() { return String.valueOf(value);}
}
public static void change(Wrapper a,Wrapper b)
{
System.out.println("before charge,a="+a+",b="+b);
int c=a.getValue();
a.setValue(b.getValue());
b.setValue(c);
//System.out.println("after charge,a="+a+",b="+b);
}
}