Java 最长运行计数程序问题

Java 最长运行计数程序问题,java,arrays,for-loop,Java,Arrays,For Loop,循环通过a的字符数组。程序应该找到给定字符的最长运行时间 我的问题是,我总是错过1个数字,或者至少在这个例子中 我使用最常见的for循环和[I]==ch&&a[I+1]==ch来比较这两个数字,如果找到匹配项,则在我有3个连续字符的实例中,它只会给我2个,因为它与I+1进行比较 我知道我不能做[I]==char,因为它不能作为程序用途 有人能帮我怎么才能得到第三个指望吗? 我不明白这里的逻辑 char [] a = {'a', 'b', 'b', 'c', 'd', 'a', 'a',

循环通过a的字符数组。程序应该找到给定字符的最长运行时间

我的问题是,我总是错过1个数字,或者至少在这个例子中

我使用最常见的for循环和[I]==ch&&a[I+1]==ch来比较这两个数字,如果找到匹配项,则在我有3个连续字符的实例中,它只会给我2个,因为它与I+1进行比较

我知道我不能做[I]==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);

}

}
char[]a={'a','b','b','c','d','a','a','a','f'};
char ch='a';
整数计数=0;
int oneTime=0;

对于(int i=0;i计算比较而不是字符的标准错误。一次处理一个字符,当它与您要查找的指定字符匹配时递增

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'};
char ch='a';
对于(inti=0;i
intmaxcount=0;
int currentCount=0;
for(int i=0;i
您是否考虑了最长运行时间为1或0的可能性?检查逻辑错误的一个好方法是说出用于解决问题的伪代码。您将如何通过迭代数组来计算运行时间?您将如何跟踪最长运行时间?为清楚起见,您只查找特定对象的最长运行时间ar字符,对吗?(在本例中是字母“a”)您不仅仅是想找到任何字符中最长的一个,是吗?顺便说一句,如果下面的答案有用,有一个复选标记将答案标记为“已接受”。谢谢。
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);
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);