It appears you have not yet registered with DEVPPL. To register please click here... (it's fast, easy and free!)

Forum

Log In Sponsors
Partner Sites
Board index Programming Java Forum

HOW TO EXCHANGE TWO VARIABLES IN FUNCTION?

HOW TO EXCHANGE TWO VARIABLES IN FUNCTION?

Postby dyingsky on Sun Mar 25, 2007 7:45 pm

hello,i am a java novice ,now i meet a problem:
how to exchange two variables in function?
in c++, we can use the point to do this,just like that:
//c++ programme
void exchange(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
int x=3,y=5;
exchange(x,y);
then the values of x and y have exchanged,but how can reach this effect in java ?
thanks!!
dyingsky
 
Posts: 4
Joined: Sun Mar 25, 2007 7:31 pm
Location: China.GuanZhou

Postby sherinetresa on Wed Mar 28, 2007 11:44 am

i think this code will help

public class exchange
{
int a,b;
exchange(int s,int r)
{
a=s;b=r;
}
public void change()
{
int temp=a;
a=b;
b=temp;

}
public static void main(String args[])
{
exchange e1=new exchange(20,30);
System.out.print("\n Before exchange");

System.out.print("\n a:"+e1.a);
System.out.print("\n b:"+e1.b);
e1.change();
System.out.print("\n After exchange ");
System.out.print("\n a:"+e1.a);
System.out.print("\n b:"+e1.b);
}
}

regards,
sherine
sherinetresa
 
Posts: 2
Joined: Wed Mar 28, 2007 11:22 am

Postby dyingsky on Wed Mar 28, 2007 5:04 pm

thanks for sherine's reply,your answer is right
but ,if there are many numbers i want to exchange,and i don't know which will be exchange firstly,which will next, how to exchange these numbers?
for example : a=1,b=2,c=3,d=4,e=5;
i want to exchange a and b firstly, then exchange c and d,then exchange e and a , …… , and so on
i want to do these in a function,how to do this?
thanks again!
ls,love you!
and i want to find a partner to practice english by talk in msn , my msn account is helnen@hotmail.com welcome you
dyingsky
 
Posts: 4
Joined: Sun Mar 25, 2007 7:31 pm
Location: China.GuanZhou


Who is online

Users browsing this forum: No registered users and 0 guests