Topic: 如何用方法改变值

  Print this page

1.如何用方法改变值 Copy to clipboard
Posted by: haozhongjie
Posted on: 2006-08-01 12:49

class help
{
public chang(object a,object b)
{
object c;
c=a;
a=b;
b=c;
}
public static void main(String [] agrs)
{
int x=6;
int y=10;
chang(x,y);
System.out.println("x="+x+" ,y="+y);
}
}
输出的结果并没有更变它们的值;请问各位大侠,如果用方法改变主函数中变量的值??谢谢

2.Re:如何用方法改变值 [Re: haozhongjie] Copy to clipboard
Posted by: leange
Posted on: 2006-08-01 13:48

一种可以实现的方法:

class Help {

private static int [] change(int a, int b) {
int c;
c = a;
a = b;
b = c;
int [] result = {a, b};
return result;
}

public static void main(String args[]) {
int a = 6;
int b = 10;
int result [] = change(a, b);
System.out.println("a=" + result[0] + " ,b=" + result[1]);
}

}

之所以会有你所说的问题,主要是方法chang()是在独立内存中处理的,而不是对main中a,b的地址引用。其实在chang()中值是有变化的,只是它的变化并没有返回给main函数。

3.Re:如何用方法改变值 [Re: haozhongjie] Copy to clipboard
Posted by: tomcatexpert
Posted on: 2006-08-01 14:44

java 的方法调用是copy by value,所以你的change()方法中a, b已经不是原来的x, y,而是新的备份。

4.Re:如何用方法改变值 [Re: haozhongjie] Copy to clipboard
Posted by: awrong
Posted on: 2006-08-19 22:45

class help{
int a,b;
help(int x,int y){
a=x;
b=y;
}
public void change(help o){
int c;
c=o.a;
o.a=o.b;
o.b=c;
}
public static void main(String [] agrs){
int x=6;
int y=10;
help ob=new help(x,y);
System.out.println("Before change: "+ob.a+" "+ob.b);
ob.change(ob);
System.out.println("After change: "+ob.a+" "+ob.b);
}
}
参数传递:1、按值;2、按引用。
按值时,方法中的操作对x,y的值没有影响,只是原来的副本,所以不会改变。
按引用,在方法中操作对象,它是指向原来的对象,将会影响原来的参数对象,所以会改变。
上例中,将要改变的值封装到一个对象中,用对象作为参数传递给change()方法,则操作是指向原来的参数对象的,所以change()方法改变了原来的值。Ok?


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923