java - 字符的出现

标签 java string counter indexof

我试图忽略不在字符串字母表中的字符,但由于某种原因 eclipse 提示,变量 i 无法解析

这是我的代码:

import java.util.Scanner;

公共(public)类 OccurenceOfCaracters {

static final int ASCII_SIZE = 256; 
static char getMaxOccuringChar(String str) 
{ 
    // Create array to keep the count of individual 
    // characters and initialize the array as 0 
    int count[] = new int[ASCII_SIZE]; 
    String alphabet = "abcdefghijklmnopqrstuvwxyz";
    int charCheck;
    // Construct character count array from the input 
    // string. 
    int len = str.length(); 
    for (int i=0; i<len; i++) 
        charCheck = alphabet.indexOf(str.charAt(i));
        if(charCheck != -1) {
            count[str.charAt(i)]++;  //Problem occurs here 
        }
    int max = -1;  // Initialize max count 
    char result = ' ';   // Initialize result 

    // Traversing through the string and maintaining 
    // the count of each character 
    for (int i = 0; i < len; i++) { 
        if (max < count[str.charAt(i)]) { 
            max = count[str.charAt(i)]; 
            result = str.charAt(i); 
        } 
    } 

    return result; 
} 


public static void main(String[] args) 
{ 
    @SuppressWarnings("resource")
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter your Text: ");
    String str = sc.nextLine(); 
    str =  str.replaceAll("\\s","").toLowerCase();
    System.out.println("Max. character is " + 
                        getMaxOccuringChar(str)); 
} 

}

最佳答案

问题在于循环。这是来自你的代码。请注意,i 位于 for 循环本地,但您没有使用 {},因此当您使用它来帮助索引count

时,以后不会看到它
for (int i = 0; i < len; i++)
         charCheck = alphabet.indexOf(str.charAt(i));
      if (charCheck != -1) {
         count[str.charAt(i)]++; // Problem occurs here
      }

关于java - 字符的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59037238/

相关文章:

java - Collections.sort() 不排序单个数字

java - Selenium 动态生长表

node.js - 将 ElGamal 加密从加密数字转换为字符串

c - 为什么我的 char 数组没有产生越界错误?我故意分配了不足的内存,但我仍然可以分配更大的字符串

php - 如何计算字符串中 "letter numbers"的总和?

java - 数据完整性违规异常 : could not insert

java - 如何在netbeans上创建Web服务?

c++ - 为什么在 C++ 中拆分字符串比 Python 慢?

python - 如何在 Python 中从字典中提取和划分值?

C# - 实时显示多行文本框计数