当前位置: 代码迷 >> J2SE >> Java书上题例,一个小疑义
  详细解决方案

Java书上题例,一个小疑义

热度:57   发布时间:2016-04-23 20:00:49.0
Java书上题例,一个小疑问~
sum.setC=sum.info.toCharArray() ;//字符串变为字符串数组,这样写编译错误,可书上是这样子的
sum.setC(sum.getInfo().toCharArray()); //我的作业就非的这样写?不然编译出错

为什么?区别在哪?


//【例5.24】
public class StringAPIDemo01{
public static void main(String args[]){
String str1 = "hello" ;
char c[] = str1.toCharArray() ; // 将一个字符串变为字符数组
for(int i=0;i<c.length;i++){
System.out.print(c[i] + "、") ; 
}
System.out.println("") ;
String str2 = new String(c) ;
String str3 = new String(c,0,3) ;
System.out.println(str2) ;
System.out.println(str3) ;
}
};
//【作业】编写程序,统计出字符串“want you to know one thing中字母N和字母O的出现次数。
class Count{
private char c[] ;
private String info;
public char[] getC() {
return c;
}
public void setC(char[] c) {
this.c = c;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public Count(String info){ //构造赋值
this.setInfo(info);
}
public void prit(){//略...
for(int i=0;i<c.length;i++){
if..
System.out.println()
}
}
};
public class Demo01{
public static  void main(String args[]){
Count  sum=new Count("want you to know one thing") ;
sum.setC=sum.info.toCharArray() ;
//串变为字符串数组,模仿书上这样写编译错误,
//这样就好了,为什么?setC(sum.getInfo().toCharArray()); 

  sum.prit();//输出统计的个数
}
}







------解决思路----------------------
//如果setC是一个char[]变量,可以这么用,意思是给setC变量赋值
sum.setC=sum.info.toCharArray(); 

//你的代码里setC是一个方法,方法调用要加括号(),意思是调用setC方法
sum.setC(sum.getInfo().toCharArray());
------解决思路----------------------
sum.setC=sum.info.toCharArray() ;//哪本书上这么写的,叫什么名字?

------解决思路----------------------
public void setC(char[] c) {
        this.c = c;
    }
这是个方法,sum.setC=sum.info.toCharArray() ;这样写明显不行。只有变量才可以这样赋值。书好好看,应该是你没看好吧。要么就是书有误。
  相关解决方案