| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 675 人关注过本帖
标题:学习Java不久,遇到这个题目希望各位高手帮忙解释一下!
只看楼主 加入收藏
mobster
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2005-12-8
收藏
 问题点数:0 回复次数:4 
学习Java不久,遇到这个题目希望各位高手帮忙解释一下!
public class Example{
  String str=new String("good");
  char[]ch={'a','b','c'};
  public static void main(String args[]){
    Example ex=new Example();
    ex.change(ex.str,ex.ch);
    System.out.print(ex.str+" and ");
    Sytem.out.print(ex.ch);
  }
  public void change(String str,char ch[]){
    str="test ok";
    ch[0]='g';
  }
}


为什么最终结果是good and gbc ,很不解,str的值没有被改,数组的值却被改了。。

搜索更多相关主题的帖子: Java 解释 
2005-12-08 21:58
wdboy
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2005-12-9
收藏
得分:0 
我想楼主想要的功能应该是显示"test ok and gbc"吧
public void change(String str,char ch[]){
    str="test ok";
    ch[0]='g';
  }
这段代码中的str变量指的是方法参数的str变量..
并不是Example类中的str变量
改成这样就行了
public void change(String str,char ch[]){
    this.str="test ok";
    ch[0]='g';
  }
2005-12-09 23:11
元味觉醒
Rank: 1
等 级:新手上路
帖 子:11
专家分:0
注 册:2005-11-28
收藏
得分:0 
好像可以吧

/attachment/15_8922.jpg" border="0" onload="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.alt='Click here to open new window\nCTRL+Mouse wheel to zoom in/out';}" onmouseover="if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7; this.style.cursor='hand'; this.alt='Click here to open new window\nCTRL+Mouse wheel to zoom in/out';}" onclick="if(!this.resized) {return true;} else {window.open('http://mmm./attachment/15_8922.jpg');}" onmousewheel="return imgzoom(this);" alt="" />
2005-12-10 03:25
zh_shen
Rank: 1
等 级:新手上路
帖 子:19
专家分:0
注 册:2005-12-6
收藏
得分:0 
因为:
public void change(String str,char ch[])
    str="test ok";
    ch[0]='g';
这段代码没有返回到主函数中。
可以把上面代码修改为:
public void change(String str,char ch[])
     return str="test ok";
     return ch[0]='g';

public String change(String str,char ch[])
     str="test ok";
     ch[0]='g';

2005-12-10 11:15
bagger
Rank: 7Rank: 7Rank: 7
等 级:贵宾
威 望:33
帖 子:891
专家分:0
注 册:2005-8-16
收藏
得分:0 

我帮你改了
编译运行都通过了:test ok and gbc
public class Example {
String str = new String("good");
char[] ch = { 'a', 'b', 'c'};
public static void main(String args[]) {
Example ex = new Example();
ex.change(ex.str, ex.ch);
System.out.print(ex.str + " and ");
System.out.print(ex.ch);
}
public String change(String str, char ch[]) {
this.str = "test ok";
this.ch[0] = 'g';
return this.str;
}
}
你的程序主要是没有返回str,把change方法一改就好了


【三元毕业设计论文】
三元论文真的只有三元钱
客服QQ:742670649
http://shop35094218./
2005-12-10 13:53
快速回复:学习Java不久,遇到这个题目希望各位高手帮忙解释一下!
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.012020 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved