java - 如何在java中运行for循环?
问题描述
我想知道为什么这段代码不运行。有什么遗漏吗?
计算"xx"
给定字符串中的个数。我们会说允许重叠,所以"xxx"
包含 2 "xx"
。
public class Drumkit {
int countXX(String str){
String a = "abcxxx";
int count = 0;
for (int i = 0; i < str.length() - 1; i++) {
if (a.substring(i, i + 2).equals("xx")) count++;
}
return count;
}
}
解决方案
你的问题不清楚。但是,您可以尝试此代码
public static void main(String[] args) {
final int count = countXX("abcxx efjxx xyzxx xx xxxx xx","xx");
System.out.println(count);
}
static int countXX(final String text, final String occurrenceOf){
int count = 0;
int fromIndex=0;
for (int i = 0; i < text.length() - 1; i++) {
int index = text.indexOf(occurrenceOf,fromIndex);
if(index >-1) {
count++;
fromIndex=index+1;
}
}
return count;
}
推荐阅读
- javascript - 使用节点 js 和 socket.io 在 mysql 数据库中插入新记录时如何通知和更新客户端
- flutter - 在颤振应用程序中实现地点选择器对话框
- yii2 - 和以前一样,即使对于经过身份验证的用户,请求也总是重定向到登录页面
- mysql - 如何选择包含多个标签的 id?
- c# - 为什么我们在c#中进行模式匹配时要声明一个额外的变量
- java - 如何设置 drawable.setBounds 方法的高度和宽度,以便在 textview 中完美地在不同设备中正确显示图像
- graphql - Graphql:有没有办法用架构上未声明的新字段更新查询?
- powershell - $host.UI.RawUI.MaxPhysicalWindowSize 与 $host.UI.RawUI.MaxWindowSize 有什么区别
- ruby-on-rails - 图片在第一次访问时不显示,但在控制台上点击检查时显示
- angular - 在将 gmail 与 ionic 3 集成时面临问题,出现运行时错误 >>Object(...) 不是函数