public static void main(String[] args) {
int a=12 ;
int b=23;
swap(a,b);
System.out.println(a+" "+b);
} static void swap(int a, int b) {
// TODO Auto-generated method stub
int c;
c=a;
b=a;
a=c;
}
这里 a和b怎么没交换??求大神赐教

解决方案 »

  1.   

    因为a 和 b是基本类型 ,传到swap只是他们的一份拷贝 ;如果需要在swap中修改,需要把他们作为数组 或者对象进去,直接看程序算啦:public class Test { public static void main(String[] args) {
    Integer a = new Integer(12);
    Integer b = new Integer(23);
    Args t = new Args(12, 23) ;
    swap(a, b);
    System.out.println("Args交换前:" + t.getA() + " " + t.getB());
    swap(t) ;
    System.out.println(a + " " + b);
    System.out.println("Args交换后:" + t.getA() + " " + t.getB());

    int [] arr = {12, 23} ;
    System.out.println("arr交换前:" + arr[0] + " " + arr[1]);
    swap(arr, 0, 1) ;
    System.out.println("arr交换后:" + arr[0] + " " + arr[1]);


    } //数组进行交换,也会影响原来的 数据
    static void swap(int [] a, int i, int j){
    int c = a[i] ;
    a[i] = a[j] ;
    a[j] = c ;
    }
    //这样子的话Args的a 和b是会有变化的,如果在方法中重新 a = new Args(1,2) ;是不会影响原来的数据的
    static void swap(Args a){
    int c ;
    c = a.getA() ;
    a.setA(a.getB()) ;
    a.setB(c) ;
        }
    //基本类型参数 ,进行修改不会对原来的数据有影响,因为此处的数据位原来的一份拷贝
    static void swap(int a, int b) {
    // TODO Auto-generated method stub
    int c;
    c = a;
    b = a;
    a = c;
    }}
    class Args{

    private   int a ;
    private   int b ;
    public int getA() {
    return a;
    }
    public void setA(int a) {
    this.a = a;
    }
    public int getB() {
    return b;
    }
    public void setB(int b) {
    this.b = b;
    }
    public Args(int a , int b){
    this.a  = a ;
    this.b  = b ;
    }

    }
      

  2.   

    首先你的swap方法没有起任何作用,因为你的main方法中操作的a,b是局部变量,只在main中能访问到,
    swap中操作的ab是你的swap方法的参数,并不是main方法中的a,b。将a,b改为成员变量即可。
    另外你的swap代码有点问题:
    int c:
    c=a;
    b=a;
    a=c;
    你把a的值付给c了,然后再把a的值付给b,最后又把c的值付给a,这样你的操作相当于把a的值付给b,a值不变。你将a,b改为成员变量运行就知道了。
    应该改为int c;
           c=b;
           this.b=a;(你操作的必须是成员变量的b,并不是你的参数b)
           this.a=c;
    这样结果就是正确的