java中2个数据的交换如何实现??

osheatangjie 2007-09-05 04:50:38
class pt
{
int x,y;
pt(int x,int y)
{
this.x=x;
this.y=y;
}
}
////////////////////////////////////////////////////////
class test
{
static void swap(int m,int n)
{
int temp;
temp=m;
m=n;
n=temp;
}

static void change(pt a,pt b)
{
pt temp;
temp=a;
a=b;
b=temp;
}

public static void main(String[] args)
{
int m1=1;
int n1=2;
swap(m1,n1);
System.out.println(m1);
System.out.println(n1);

pt p1=new pt(1,2);
pt p2=new pt(3,4);
change(p1,p2);
System.out.println(p1.x);
System.out.println(p1.y);
System.out.println(p2.x);
System.out.println(p2.y);
}
}

//输出1 2 1 2 3 4,问想输出2 1 3 4 1 2要怎么写??忘高手指点~~~
...全文
287 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
renshaopoi 2007-09-05
  • 打赏
  • 举报
回复
这是C#里面的 吧
lfcai 2007-09-05
  • 打赏
  • 举报
回复
学习下~~~~~~~~
osheatangjie 2007-09-05
  • 打赏
  • 举报
回复
知道了,谢谢hzalan()^__^
hzalan 2007-09-05
  • 打赏
  • 举报
回复
class pt {
int x, y;
pt(int x, int y) {
this.x = x;
this.y = y;
}
}


public class Test {
void change(pt p)
{
int temp;
temp=p.x;
p.x=p.y;
p.y=temp;
}

public static void main(String[] args) {
Test h = new Test();
int a = 1, b = 2;
pt p = new pt(a,b);
System.out.println(a+ "" + "" + b);
h.change(p);
a=p.x;
b=p.y;
System.out.println(a + "" + "" + b);
}
}
Camelh 2007-09-05
  • 打赏
  • 举报
回复
java中所有的函数参数传递都是值传递
hzalan 2007-09-05
  • 打赏
  • 举报
回复
打印结果:
12
21
看到change我想起某本书上有过。
hzalan 2007-09-05
  • 打赏
  • 举报
回复
class pt {
int x, y;
pt(int x, int y) {
this.x = x;
this.y = y;
}
}


public class Test {
void change(pt p)
{
int temp;
temp=p.x;
p.x=p.y;
p.y=temp;
}

public static void main(String[] args) {
Test h = new Test();
int a = 1, b = 2;
pt p = new pt(a,b);
System.out.println(p.x + "" + "" + p.y);
h.change(p);
System.out.println(p.x + "" + "" + p.y);
}
}

参照一下吧

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧