交换两个int在c++中可以写:
void swap(int* x, int* y)
{ int temp;
temp=*x;
*x=*y;
*y=temp;}
但java中没有引用和指针,要完成同样的功能应该怎样写呢?
void swap(int* x, int* y)
{ int temp;
temp=*x;
*x=*y;
*y=temp;}
但java中没有引用和指针,要完成同样的功能应该怎样写呢?
解决方案 »
- 紧急求助:怎样让JTextField只能输入数字,并且输入指定范围的数字?
- InputStreamReader + FileInputStream 跟 Reader应用于文本文件有区别吗?
- 加入第三方库的问题
- 问大家一个反射的问题
- 请教个Applet问题
- [200分]求一JAVA 代码
- preparedStatement中怎么样传如 in(?)中的参数啊
- 最简单的小Applet,在jb中可以运行,离开JB环境后在IE和DOS中就不能运行的问题?
- 下一步应该做什么??欢迎有经验的java高手进入
- 请问如果把字符串“1234”转换成INT型的呢?谢谢
- 把word和txt文件上传到oracle数据库中保存????100分!!急救
- 网络通信安全的问题
void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
public void swap(int x,int y){
int temp=null;
temp=x;
x=y;
y=temp;
}
temp=x;
x=y;
y=temp;是直接赋值啊....
{
public static void main(String []args)
{
int a = 1;
int b = 2; System.out.println("a: " + a);
System.out.println("b: " + b); swap(a, b); System.out.println("Swapped!");
System.out.println("a: " + a);
System.out.println("b: " + b);
} public static void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
}运行结果
a:1
b:2
Swapped!
a:1
b:2怎么改变了?
这涉及的是JAVA中值传递的问题....由于基本类型是值传递...直接swap不可以
要么用INT数组传递引用...要不通过外部内联的方式
public class Test {
public static void main(String[] args) {
Test t = new Test(1,2);
System.out.println("i: " + t.i);
System.out.println("j: " + t.j); t.swap(); System.out.println("Swapped!");
System.out.println("i: " + t.i);
System.out.println("j: " + t.j);
}
int i,j;
public Test(int i,int j){
this.i = i;
this.j = j;
}
public void swap() {
int temp;
temp = i;
i = j;
j = temp;
}
}