首页 > 解决方案 > 字符的出现

问题描述

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

这是我的代码:

import java.util.Scanner;

公共类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)); 
} 

}

标签: javastringcounterindexof

解决方案


问题在于循环。这来自您的代码。请注意ifor 循环是本地的,但您没有使用 {},因此稍后使用它来帮助索引时不会看到count

for (int i = 0; i < len; i++)
         charCheck = alphabet.indexOf(str.charAt(i));
      if (charCheck != -1) {
         count[str.charAt(i)]++; // Problem occurs here
      }

推荐阅读