package interview_programs;
public class Swapping {
int x,y ;
Swapping(int a, int b){
int x = a;
int y = b;
System.out.println("the valueof x is" + x);
System.out.println("the valueof y is" + y);
}
public void replace(){
x = x + y;
y = x - y;
x = x - y;
System.out.println("the value after swap");
System.out.println("the valueof x is" + x);
System.out.println("the valueof y is" + y);
}
public static void main (String args[]) {
Swapping Swap = new Swapping(10,5);
Swap.replace();
}
}这是控制台上的输出。
输出:
X is10值
Y is5的值
掉期后的价值
X is0值
Y is0的值
发布于 2016-11-13 18:59:58
从x和y中取出int,它们创建局部变量,而不是设置本地类字段。
Swapping(int a, int b){
x = a;
y = b;
System.out.println("the valueof x is" + x);
System.out.println("the valueof y is" + y);
}发布于 2016-11-13 18:58:49
您不初始化类级别x和y,而是初始化构造函数中的本地x和y。
将'int = a‘改为'x = a’,'int = b‘改为'y = b’。
https://stackoverflow.com/questions/40577556
复制相似问题