循环遍历a的字符数组。程序应该找到给定字符的最长游程。
我遇到的问题是我总是错过1个数字,或者至少在这个例子中是这样。
我使用了最常见的ai==ch && ai+1==ch循环来比较两个数字,如果发现匹配,我在有3个连续字符的情况下执行count++,它只会给我2,因为它与i+1进行比较。
我知道我不能做ai==char,因为它不能作为编程的目的。
谁能帮帮我,我怎么才能数到第三个数呢?
我忽略了这里的逻辑或其他什么。
char [] a = {'a', 'b', 'b', 'c', 'd', 'a', 'a', 'a', 'f'};
char ch = 'a';
int count = 0;
int oneTime = 0;
for(int i = 0; i<a.length; i++){
System.out.print(a[i]);
System.out.print(" ");
}
System.out.println(" ");
for(int i = 0; i<a.length-1; i++){
if(a[i]==ch && a[i+1]==ch){
count++;
}//end of if
if(oneTime ==0)
if(a[a.length-2]==a[a.length-1]){
count++;
oneTime++;
}
}
System.out.print(count);
}
}发布于 2013-12-01 07:30:23
计算比较而不是计算字符的标准错误。每次处理一个字符,并在它与您正在查找的指定字符匹配时递增。
char [] a = {'a', 'b', 'b', 'c', 'd', 'a', 'a', 'a', 'f'};
char ch = 'a';
for(int i = 0; i<a.length; i++){
System.out.print(a[i]);
System.out.print(" ");
}
System.out.println(" ");
int count = 0;
int largest = 0;
for(int i = 0; i<a.length; i++){
if(a[i]==ch){
count++;
}
else {
count = 0;
}
//now remember if this is the longest span
if (count > largest) {
largest = count;
}
}
System.out.print("The longest run is: "+largest);上面的代码将查找指定字符的最长游程。
如果您想要查找任意字符的最长游程,请尝试执行以下操作:
char [] a = {'a', 'b', 'b', 'c', 'd', 'a', 'a', 'a', 'f'};
for(int i = 0; i<a.length; i++){
System.out.print(a[i]);
System.out.print(" ");
}
System.out.println(" ");
char ch = a[0];
int count = 1;
int largest = 1;
//note we skip the first character
for(int i = 1; i<a.length; i++){
if(a[i]==ch){
count++;
}
else {
//reset with this char as first of a new run
ch = a[i];
count = 1;
}
//now remember if this is the longest span
if (count > largest) {
largest = count;
}
}
System.out.print("The longest run is: "+largest);发布于 2013-12-01 07:30:28
int maxCount = 0;
int currentCount = 0;
for(int i = 0; i < a.length-1; i++){
if(a[i] == a){
currentCount++;
if(maxCount < currentCount){
maxCount = currentCount;
}
}
else {
currentCount = 0;
}
}
System.out.print(maxCount);https://stackoverflow.com/questions/20306802
复制相似问题