有返回值有参数的函数调用问题

凉岑玉 2010-04-29 07:08:04
代码如下~
public int countSubstring() {
String p = "abababa";
String c = "a";
int sum = 0;
int len = p.length();
for (int i = 0; i < len; i++) {
if (p.indexOf(c) >= 0) {
sum++;
p = p.substring((p.indexOf(c) + 1));
}

}

return sum;


}





public static void main(String[] args) {
// TODO Auto-generated method stub
HelloWorld1 hello=new HelloWorld1();
hello.countSubstring();

}

//为什么在运行时不能实现调用?
请高手指教
...全文
203 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Mars_Ma_OK 2010-04-29
  • 打赏
  • 举报
回复
楼上的下手这么快呀 看来我只有顶起了!!! 嘿嘿!
凉岑玉 2010-04-29
  • 打赏
  • 举报
回复
楼上的~写了!
keeya0416 2010-04-29
  • 打赏
  • 举报
回复
看楼主的代码很像是求c在p中的数量啊
没必要这么麻烦

package com.keeya.util;

public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
HelloWorld1 hello = new HelloWorld1();
System.out.println(hello.countSubstring());
}
}

class HelloWorld1 {
public int countSubstring() {
String p = "abababa";
String c = "a";
int sum = 0;
int len = p.length();
for (int i = 0; i < len; i++) {
if (Character.toString(p.charAt(i)).equals(c)) {
sum++;
}
}
return sum;
}
}
keeya0416 2010-04-29
  • 打赏
  • 举报
回复
能调用啊
你是不是想问为什么调用没反应了?
你这方法内部没有输出的东西 返回了你也不能看到
lunbing 2010-04-29
  • 打赏
  • 举报
回复
你的代码没问题,可以正常运行,只是没打印结果:System.out.println(hello.countSubstring());
其实可以不用循环,这样写:
public int countSubstring()
{
String p = "abababa";
String c = "a";
if (p.endsWith(c))
{
return p.split(c).length;
}
else
{
return p.split(c).length -1;
}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧