user12393834
user12393834

Reputation:

Occurrence of Characters

I am trying to ignore Charakter which are not in the String Alphabet, but for some reason eclipse complains, that the Variable i cannot be resolved

Here is my Code:

import java.util.Scanner;

public class 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)); 
} 

}

Upvotes: 0

Views: 35

Answers (1)

WJS
WJS

Reputation: 40034

The problems is the loop. This is from your code. Note the i is local to the for loop but you didn't use {} so it isn't seen later when you use it to help index count

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

Upvotes: 1

Related Questions