B
Bill Reyn
I know we have been over this before, but I still don't get it./*
How can you swap two integers in Java? - in C++ I can swap references
with 3 lines of code - but how on earth am I supposed to do it in
Java, the code below works, but cannot be the right way of doing it.
Why not?
--------------------------------------------------------------------
/* this swaps 2 integers correctly, BUT its seems non-OO */
class Swap4
{
static int x=5, y=7 ; // this looks horrid!
public static void main(String [] args){
WorkItOut w = new WorkItOut();
w.swaps(x,y);
System.out.println( " x (was 5)now is " + x + " y (was 7) now is " +
y);
}
}
class WorkItOut
{
void swaps(int p, int q){
Swap4 s = new Swap4();
s.x = q;
s.y = p; }
}
---------------------------------------------------------------
If your interested in Cplusplus its simply:
void SwapInt( int &nA, int &nB)
{
int nC;
nC = nA;
nA = nB;
nB = nC;
}
How can you swap two integers in Java? - in C++ I can swap references
with 3 lines of code - but how on earth am I supposed to do it in
Java, the code below works, but cannot be the right way of doing it.
Why not?
--------------------------------------------------------------------
/* this swaps 2 integers correctly, BUT its seems non-OO */
class Swap4
{
static int x=5, y=7 ; // this looks horrid!
public static void main(String [] args){
WorkItOut w = new WorkItOut();
w.swaps(x,y);
System.out.println( " x (was 5)now is " + x + " y (was 7) now is " +
y);
}
}
class WorkItOut
{
void swaps(int p, int q){
Swap4 s = new Swap4();
s.x = q;
s.y = p; }
}
---------------------------------------------------------------
If your interested in Cplusplus its simply:
void SwapInt( int &nA, int &nB)
{
int nC;
nC = nA;
nA = nB;
nB = nC;
}